Qt5:获取列表视图中点击项的值

Qt5 : Get value of item clicked in a listview

本文关键字:获取 列表 视图 Qt5      更新时间:2023-10-16

我正在制作一个Qt5.7应用程序,在从文件中读取内容后填充QListView。下面是它的确切代码。

QStringListModel *model;
model = new QStringListModel(this);
model->setStringList(stringList); //stringList has a list of strings
ui->listView->setModel(model);
ui->listView->setEditTriggers(QAbstractItemView::NoEditTriggers); //To disable editing

现在在我设置的QListView中显示列表很好。我现在需要做的是获取被双击的字符串并在其他地方使用该值。我该怎么做呢?

我试着做的是通过这种方式将侦听器附加到QListView

... // the rest of the code
connect(ui->listView, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(fetch()));
...

然后是函数fetch

void Window::fetch () {
  qDebug() << "Something was clicked!";
  QObject *s = sender();
  qDebug() << s->objectName();
}

但是,objectName()函数返回"listView",而不是listView项或索引。

信号已经为您提供了点击的QModelIndex

所以你应该把你的slot改成:

void Window::fetch (QModelIndex index)
{
....

QModelIndex现在有一个列和行属性。因为列表没有列,所以您对该行感兴趣。这是所单击项的索引。

//get model and cast to QStringListModel
QStringListModel* listModel= qobject_cast<QStringListModel*>(ui->listView->model());
//get value at row()
QString value = listModel->stringList().at(index.row());

您应该添加索引作为插槽的参数。您可以使用该索引访问列表

你的代码应该是这样的:

void Window::fetch (QModelIndex index) { /* Do some thing you want to do*/ }