我在窗口中创建了一个QTreeView,我希望在双击时获取所选项目的文本。我尝试使用信号“doubleClicked(const QModelIndex&)”来获取所选项目的索引。
但是当我收到信号并希望对传入的索引执行某些操作时,我无法正确获取该项目。
我发现传入的索引是这样的:
根
| ... item1(0,0)
| ... | ... subItem1(0,0)
| ... | ... subitem2(1,0)
| ... item2(1,0)
有两个(0,0)和(1,0)项?编辑:我得到了这个结果
qDebug(QString::number(index.row()).toLatin1().data()); // row
qDebug(QString::number(index.column()).toLatin1().data()); // column
这是我的代码,创建QTreeView和QStandardItemModel:
mTree = new QTreeView(this); // mTree is a class member
treeModel = new QStandardItemModel(); // also a class member
proxymodel = new MySortFilterProxyModel(); // for sorting
proxymodel->setSourceModel(treeModel);
mTree->setModel(proxymodel);
和一个接收信号的自定义插槽:
private slots:
void getSelectedIP(const QModelIndex &);
连接信号和插槽:
connect(mTree, SIGNAL(doubleClicked(const QModelIndex &)),
this, SLOT(getSelectedIP(const QModelIndex &)));
插槽的实现,以及在此代码中崩溃的程序:
void HostTreeFrame::getSelectedIP(const QModelIndex &index)
{
QStandardItem *selectedItem = treeModel->itemFromIndex(index);
qDebug(QString::number(index.row()).toLatin1().data());
qDebug(QString::number(index.column()).toLatin1().data());
qDebug("1");
QString selectedIPString = selectedItem->text(); // program crashed here, selectedItem == nullptr
qDebug("2");
}
编辑:selectedItem
是nullptr
,这就是程序崩溃的原因,但为什么它是nullptr?
考虑代码......
void HostTreeFrame::getSelectedIP(const QModelIndex &index)
{
QStandardItem *selectedItem = treeModel->itemFromIndex(index);
问题是index
与视图使用的模型相关联,但这是代理模型 - 而不是QStandardItemModel
。
您需要将模型索引索引映射到正确的模型。所以像......
void HostTreeFrame::getSelectedIP(const QModelIndex &index)
{
auto standard_item_model_index = proxymodel->mapToSource(index);
QStandardItem *selectedItem = treeModel->itemFromIndex(standard_item_model_index);
/*
* Check selectedItem before dereferencing.
*/
if (selectedItem) {
...
上面的代码假设proxymodel
是HostTreeFrame
的成员(或直接可见)。