您当前的位置: 首页 >  qt

txwtech

暂无认证

  • 2浏览

    0关注

    813博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

QT模型索引使用QModelIndex

txwtech 发布时间:2022-10-03 21:46:50 ,浏览量:2

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 
#include 
#include 
#include 
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()            
关注
打赏
1665060526
查看更多评论
0.0421s