【问题标题】:How to get the text of selected item from QListView in QT? [duplicate]如何从 QT 中的 QListView 获取所选项目的文本? [复制]
【发布时间】:2015-08-28 06:20:30
【问题描述】:

我需要将QListView 中的选定项目名称作为QString 获取。我已经尝试谷歌,但我没有发现任何有用的东西。

我的QListViewModel 及其填充方法如下:

QString setting_path = QDesktopServices::storageLocation(QDesktopServices::DataLocation);

QStandardItemModel *model2=new QStandardItemModel();

QFile file(setting_path+"history.txt");
if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
    return;

QTextStream in(&file);

while(!in.atEnd()) {
QString line = in.readLine();
QList<QStandardItem *> items;
QStringList fields = line.split(">");
QStringList fields3 = fields.filter("");

foreach (QString text, fields3)
{
    items.append(new QStandardItem((QString)text));
}

if(items.length() > 0)
{
    model2->appendRow(items);
}
}
 ui->listView->setModel(model2);
}

【问题讨论】:

    标签: c++ qt qt4


    【解决方案1】:

    我想,你可以用selectedIndexes()这个

    QModelIndexList QListView::selectedIndexes() const;
    

    所以,当您需要获取项目时 - 只需调用此方法并从您的模型中获取项目(通过您的访问器,或通过使用 data(index) 与您的/系统角色,或通过任何方式获取按行和列的索引项。

    例如,这是如何获取第一项:

    void MyListView::somethingIsSelected() {
        const auto selectedIdxs = selectedIndexes();
        if (!selectedIdxs.isEmpty()) {
            const QVariant var = model()->data(selectedIdxs.first());
            // next you need to convert your `var` from `QVariant` to something that you show from your data with default (`Qt::DisplayRole`) role, usually it is a `QString`:
            const QString selectedItemString = var.toString();
    
            // or you also may do this by using `QStandardItemModel::itemFromIndex()` method:
            const QStandardItem* selectedItem = dynamic_cast<QStandardItemModel*>(model())->itemFromIndex(selectedIdxs.first());
            // use your `QStandardItem`
        }
    }
    

    【讨论】:

      【解决方案2】:

      用以下代码解决:

      void hist::on_listView_clicked(const QModelIndex &index)
      {
          QModelIndexList templatelist = ui->listView
                                           ->selectionModel()
                                           ->selectedIndexes();
          QStringList stringlist;
          foreach (const QModelIndex &index, templatelist){
              stringlist.append(index.data(Qt::DisplayRole).toString());
          }
          qDebug() << stringlist.join(",");
      }
      

      谢谢大家!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-03-21
        • 2020-07-08
        • 1970-01-01
        • 2012-06-22
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多