【问题标题】:Can't get item from QTreeView by QModelIndex无法通过 QModelIndex 从 QTreeView 获取项目
【发布时间】:2019-04-12 09:06:56
【问题描述】:

我在一个窗口中创建了一个 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 &)));

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?

【问题讨论】:

  • 请提供MCVE。具有 Qt 知识的人可能能够按原样帮助您,但通常您希望减少您的问题。无论如何,您检查过selectedItem 的值吗?是nullptr吗?否则,你用过调试器吗?

标签: c++ qt qtreeview qstandarditemmodel


【解决方案1】:

考虑代码...

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) {
        ...

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多