无法通过QModelIndex从QTreeView获取项目

时间:2019-04-12 09:06:56

标签: c++ qt qtreeview qstandarditemmodel

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

但是,当我收到信号并想对传入的索引执行某些操作时,我无法正确获取该项目。

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

| ... item1(0,0)

| ... | ... subItem1(0,0)

| ... || subitem2(1、0)

| ... item2(1,0)

有两个(0,0)和(1,0)项目??? 编辑:我得到了这个结果

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {

    guard let selectedImage = info[.editedImage] as? UIImage else {
        fatalError("Expected a dictionary containing an image, but was provided the following: \(info)")
    }

    self.myImageView.image = selectedImage

    picker.dismiss(animated: true, completion: nil)
}

这是我的代码,创建QTreeView和QStandardItemModel:

<div class="name">
    "by "
    <em>Some Author</em>
    ", "
    <em>Another Author</em>
</div>

和用于接收信号的自定义插槽:

qDebug(QString::number(index.row()).toLatin1().data()); // row
qDebug(QString::number(index.column()).toLatin1().data()); // column

连接信号和插槽:

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"); } ,这就是程序崩溃的原因,但是为什么它是nullptr?

1 个答案:

答案 0 :(得分:0)

考虑代码...

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的成员(或对其直接可见)。