gpt4 book ai didi

c++ - 无法通过 QModelIndex 从 QTreeView 获取项目

转载 作者:行者123 更新时间:2023-11-28 04:20:06 25 4
gpt4 key购买 nike

我在一个窗口中创建了一个 QTreeView,我想在双击它们时获取所选项目的文本。我尝试使用信号“doubleClicked(const QModelIndex &)”来获取所选项目的索引。

但是当我收到信号并想对传入的索引做一些事情时,我无法正确获取该项目。

我发现传入的索引是这样的:

|...项目 1 (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 &)));

slot的实现,这段代码程序崩溃了:

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");
}

编辑:selectedItemnullptr,这就是程序崩溃的原因,但为什么是nullptr?

最佳答案

考虑代码...

void HostTreeFrame::getSelectedIP(const QModelIndex &index)
{
QStandardItem *selectedItem = treeModel->itemFromIndex(index);

问题是 index 与 View 使用的模型相关联,但这是代理模型——而不是 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) {
...

上面的代码假定 proxymodelHostTreeFrame 的成员(或直接可见)。

关于c++ - 无法通过 QModelIndex 从 QTreeView 获取项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55648131/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com