Qt Model/view 小例項 檔案目錄瀏覽器
阿新 • • 發佈:2021-07-15
1. 檔案目錄瀏覽器
直接在main.cpp檔案中新增下列程式碼
#include "mainwindow.h" #include <QApplication> #include <QAbstractItemModel> #include <QAbstractItemView> #include <QItemSelectionModel> #include <QDirModel> #include <QTreeView> #include <QListView> #include <QTableView> #include <QSplitter> // MV model view int main(int argc, char* argv[]) { QApplication a(argc, argv); //首先建立一個檔案模型 QDirModel model; //三種顯示模式 QTreeView tree; QListView list; QTableView table; // 設定view物件的model tree.setModel(&model); list.setModel(&model); table.setModel(&model); tree.setSelectionMode(QAbstractItemView::SingleSelection); //單選 // tree.setSelectionMode(QAbstractItemView::MultiSelection); //多選 list.setSelectionMode(QAbstractItemView::MultiSelection); //多選 // table.setSelectionMode(tree.selectionModel()); //多選 table.setSelectionMode(QAbstractItemView::MultiSelection); //多選 QObject::connect(&tree, SIGNAL(doubleClicked(QModelIndex)), &list, SLOT(setRootIndex(QModelIndex))); QObject::connect(&tree, SIGNAL(doubleClicked(QModelIndex)), &table, SLOT(setRootIndex(QModelIndex))); QSplitter* splitter = new QSplitter; // 添加布局 splitter->addWidget(&tree); splitter->addWidget(&list); splitter->addWidget(&table); splitter->setWindowTitle(QObject::tr("Model/View")); splitter->show(); return a.exec(); }
為了實現雙擊QTreeView物件中的某個目錄時,QListView物件和QTableView物件中顯示此選定目錄下的所有檔案和目錄,需要連線QTreeView物件的doubleClicked()訊號與QListView物件和QTableView物件的setRootIndex()槽函式。
QObject::connect(&tree, SIGNAL(doubleClicked(QModelIndex)), &list, SLOT(setRootIndex(QModelIndex))); QObject::connect(&tree, SIGNAL(doubleClicked(QModelIndex)), &table, SLOT(setRootIndex(QModelIndex)));
其中 setRootIndex的介紹如下
QModelIndex的介紹如下
QModelIndex類用於定位資料模型中的資料。
doubleClicked訊號如下,這個訊號不是在tree裡面的而是QAbstractItemView裡面的
QAbstractItemView::doubleClicked(const QModelIndex &index)
This signal is emitted when a mouse button is double-clicked. The item the mouse was double-clicked on is specified by index. The signal is only emitted when the index is valid.
這個訊號在雙擊滑鼠按鈕時發出。滑鼠雙擊的專案由index指定。該訊號只在索引有效時發出。