Qt5:获取列表视图中点击项的值
Qt5 : Get value of item clicked in a listview
我正在制作一个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*/
}
相关文章:
- Qt - QVector 和模型视图 - 从列表视图获取自定义类的最佳方法是什么?
- 如何在 c++ stl 中获取列表中被推回的元素的地址,在常量时间内?
- 如何获取列表的每个对象并调用getName方法来打印其名称
- 如何获取列表中有子项的树的节点总和?
- 如何获取列表命令的响应消息(从CFTPConnection)
- 如何获取列表中的倒数第二个元素
- 如何从迭代器获取列表
- 获取列表数组中的所有列表项
- 获取列表的第一个和最后一个元素<string>给我非法指令错误
- 如何概括精神解析器以任意顺序获取列表
- 我想通过递归获取列表元素的所有置换
- Tcl API 如何从 Tcl 获取列表
- 如何使用迭代器来获取列表的值?
- 获取列表<节点*>中的字符并返回
- 如何在c++中获取列表
- Qt5:获取列表视图中点击项的值
- 获取c++列表中正在迭代的当前对象
- 获取c++列表迭代器值的问题
- C++ |获取列表中的最后一个值
- 获取列表中元素的个数