当前位置: 动力学知识库 > 问答 > 编程问答 >

c++ - Renaming QTreeView Items

问题描述:

I have been looking around for quite a while now and I haven't been able to find a solution for trying to Rename items in a QTreeView. Basically what I mean by this is when you double click something in the QTreeView you get the option of renaming the item. When the user is done editing the name I need a signal that will tell me the index into the tree or the QStandardItem that was edited so I can change that particular items name that is attached to the QStandardItem.

This might be a little to vague, I can't really provide my source for this because it would require me to give you my entire project which is a couple gigs.

If you need me to explain anything else I'll try my best, I'll also include an image of what I'm talking about for a better understanding.

Double Click Renaming

网友答案:

Basically what I mean by this is when you double click something in the QTreeView you get the option of renaming the item.

Use the setFlags() function of QStandardItem to set Qt::ItemIsEditable:

#include <QtWidgets>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    QMainWindow w;
    QTreeView *treeView = new QTreeView;
    QStandardItemModel model(4, 1);
    for (int row = 0; row < 4; ++row) {
        QStandardItem *item = new QStandardItem(QString("row %0").arg(row));
        item->setFlags(item->flags() | Qt::ItemIsEditable);
        model.setItem(row, 0, item);
    }
    treeView->setModel(&model);
    w.setCentralWidget(treeView);
    w.show();

    return a.exec();
}

OR'ing the Qt::ItemIsEditable flag with the existing flags is important, because otherwise you'll end up with disabled items. For example, here are the flags after OR'ing with the existing ones:

QFlags<Qt::ItemFlags>(ItemIsSelectable|ItemIsEditable|ItemIsDragEnabled|ItemIsDropEnabled|ItemIsEnabled)

And without the existing ones:

QFlags<Qt::ItemFlags>(ItemIsEditable)

When the user is done editing the name I need a signal that will tell me the index into the tree or the QStandardItem that was edited so I can change that particular items name that is attached to the QStandardItem.

You can connect to the dataChanged() signal of QStandardItemModel:

QObject::connect(&model, SIGNAL(itemChanged(QStandardItem*)),
    &myObject, SLOT(onItemChanged(QStandardItem*)));
分享给朋友:
您可能感兴趣的文章:
随机阅读: