QT模型索引使用QModelIndex
QModelIndex有三个要素:行row 列column 父节点索引parent
但是注意我们并不能定义一个QModelIndex
QModelIndex的构造函数QModelIndex()的功能是创建一个新的空的QModelIndex
QModelIdex()是一个空索引,它其实可以代表任意model中的顶层节点,例如TableModel中每个Item的父节点都是顶层节点,所以每个Item的索引中的parent都是QModelIndex;
可以获得QModelIndex 的方法有两种:
1.通过Model中的成员函数index()取得,
2.通过和Model绑定的View的成员函数取得,
举例:
class TabelModel : pulic QAbstractTableModel
auto table = new TableModel();
auto tableView = new QTableView();
tableView.setModel(table);
QModelIndex index1 = tableView.currentIndex ();//
//QModelIndex Model::index(int row, int column, QModelIndex parent)
QModelIndex index2 = tabel.index(0,0,QModelIndex());//
pro文件添加:
QT+=widgets
SOURCES += \
main.cpp
#include <QApplication>
#include <QTreeView>
#include <QDebug>
#include <QStandardItemModel>
int main(int argc, char *argv[])
{QApplication app(argc,argv);QStandardItemModel model;//创建标准项模型QStandardItem *parentItem=model.invisibleRootItem();//获取模型的根项(root Item),根项是不可见的QStandardItem *item0=new QStandardItem;//创建标准项0,并设置显示文本,图标和工具提示item0->setText("A");QPixmap pixmap0(50,50);pixmap0.fill("red");item0->setIcon(QIcon(pixmap0));item0->setToolTip("indexA");parentItem->appendRow(item0);//将创建的标准项作为根项的子项parentItem=item0;//将创建的标准项作为新的父项//创建新的标准项,它将作为item0的子项QStandardItem *item1=new QStandardItem;item1->setText("B");QPixmap pixmap1(50,50);pixmap1.fill("blue");item1->setIcon(QIcon(pixmap1));item1->setToolTip("indexB");parentItem->appendRow(item1);//创建新的标准项,这里使用另外一种方法来这是文本,图标和工具提示QStandardItem *item2=new QStandardItem;QPixmap pixmap2(50,50);pixmap2.fill("green");item2->setData("C",Qt::EditRole);item2->setData("indexC",Qt::ToolTipRole);item2->setData(QIcon(pixmap2),Qt::DecorationRole);parentItem->appendRow(item2);//在树型视图中显示模型QTreeView view;view.setModel(&model);view.show();//获取item0的索引并输出item0的子项数目,然后输出了item1的显示文本和工具提示QModelIndex indexA=model.index(0,0,QModelIndex());qDebug()<<"indexA row count:"<<model.rowCount(indexA);QModelIndex indexB=model.index(0,0,indexA);qDebug()<<"indexB text:"<<model.data(indexB,Qt::EditRole).toString();
qDebug()<<"indexB toolTip:"<<model.data(indexB,Qt::ToolTipRole).toString();return app.exec();
}