1,简介
之前介绍了QTreeView的初始化和常用设置,现在数据已经显示出来了。
那么QTreeView上如何处理选中、单击双击、右键菜单等操作呢?
本文介绍选中信号的处理。
2,选中相关信号
QTreeView的选中内容由一个封装的QItemSelectionModel管理,通过QTreeView接口selectionModel()可以取得该Model指针。
该Model存在这些信号:
Q_SIGNALS: void selectionChanged(const QItemSelection &selected, const QItemSelection &deselected); void currentChanged(const QModelIndex ¤t, const QModelIndex &previous); void currentRowChanged(const QModelIndex ¤t, const QModelIndex &previous); void currentColumnChanged(const QModelIndex ¤t, const QModelIndex &previous); void modelChanged(QAbstractItemModel *model);
一般如果设置选中模式为单个元素,那么使用currentChanged信号即可;
如果是单行,那么使用currentRowChanged信号即可;
如果是多选,一般使用selectionChanged信号。
其他不常用,使用方法类似,根据情况选用。
3,槽函数处理
1,定义对应的槽函数(这里3个信号都处理,是为了演示用法,实际一般只处理其中一种信号)
private: void slotSelectionChanged(const QItemSelection &selected, const QItemSelection &deselected); void slotCurrentChanged(const QModelIndex ¤t, const QModelIndex &previous); void slotCurrentRowChanged(const QModelIndex ¤t, const QModelIndex &previous);
2,绑定信号
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); InitTree(); connect(ui->treeView->selectionModel(),&QItemSelectionModel::selectionChanged,this,&MainWindow::slotSelectionChanged); connect(ui->treeView->selectionModel(),&QItemSelectionModel::currentChanged,this,&MainWindow::slotCurrentChanged); connect(ui->treeView->selectionModel(),&QItemSelectionModel::currentRowChanged,this,&MainWindow::slotCurrentRowChanged); }
3,槽函数实现
//选中内容变化,覆盖单选和多选的情况 void MainWindow::slotSelectionChanged(const QItemSelection &selected, const QItemSelection &deselected) { QItemSelectionModel *selections = ui->treeView->selectionModel(); QModelIndexList indexes = selections->selectedIndexes(); //得到所有选中的index foreach(QModelIndex index, indexes) { //从索引index获取item指针,mModel是tree的数据Model,这里是QStandardItemModel*类型 QStandardItem* item = mModel->itemFromIndex(index); if (item) { //你的操作,比如取文本、取附带的data // QString text = item->text(); // QString data1 = item->data(Qt::UserRole + 1).toString(); // QString data2 = item->data(Qt::UserRole + 2).toInt(); } } } //当前选中index变化,单个 void MainWindow::slotCurrentChanged(const QModelIndex ¤t, const QModelIndex &previous) { QStandardItem* item = mModel->itemFromIndex(current); if (item) { //你的操作,同上 } } //当前选中行变化,单行 void MainWindow::slotCurrentRowChanged(const QModelIndex ¤t, const QModelIndex &previous) { //取选中的这行的第一个元素的index QModelIndex index = current.sibling(current.row(),0); QStandardItem* item = mModel->itemFromIndex(index); if(item) { //你的操作,同上 } }