QT MVC 模型/视图
1、 模型视图实例一, QFileSystemModel QTreeView ,model/view示例。
#include <QApplication> #include <QFileSystemModel> #include <QTreeView> #include <QListView> #include <QStandardItemModel> #include <QDebug> int main(int argc, char *argv[]) { QApplication a(argc, argv); QFileSystemModel model; model.setRootPath("/"); QTreeView tree; tree.setModel(&model); tree.setRootIndex(model.index("/")); tree.setFixedSize(500, 400); tree.show(); return a.exec(); }
2. QStandardItemModel 模型
#include "dialog.h" #include <QApplication> #include <QFileSystemModel> #include <QTreeView> #include <QListView> #include <QStandardItemModel> #include <QDebug> int main(int argc, char *argv[]) { QApplication a(argc, argv); QStandardItemModel model; QStandardItem *parentItem = model.invisibleRootItem(); QStandardItem *item0 = new QStandardItem; item0->setText("A"); QPixmap pixmap0(50, 50); pixmap0.fill("red"); item0->setIcon(QIcon(pixmap0)); item0->setToolTip("indexA"); parentItem->appendRow(item0); parentItem = item0; QStandardItem *item1 = new QStandardItem; item1->setText("B"); QPixmap pixmap1(50, 50); pixmap1.fill("green"); item1->setIcon(QIcon(pixmap1)); item1->setToolTip("indexB"); parentItem->appendRow(item1); QStandardItem *item2 = new QStandardItem; item2->setText("C"); QPixmap pixmap2(50, 50); pixmap2.fill("blue"); item2->setIcon(QIcon(pixmap2)); item2->setToolTip("indexC"); parentItem->appendRow(item2); QTreeView view; view.setModel(&model); view.show(); QModelIndex indexA = model.index(0,0,QModelIndex()); qDebug() << "indexA row count: " << model.rowCount(indexA); QModelIndex indexB = model.index(1,0,indexA); qDebug() << "indexB text: " << model.data(indexB, Qt::EditRole).toString(); return a.exec(); }