如何将 QModelIndex 设置为 QListView

Posted

技术标签:

【中文标题】如何将 QModelIndex 设置为 QListView【英文标题】:How to set QModelIndex to QListView 【发布时间】:2019-05-14 19:25:35 【问题描述】:

我真的是 QT 的菜鸟,所以对我放轻松 所以我有 2 个 QListviews 1.时间清单 2. 日期列表 我想要做的是,当我在 Timelist 中选择一个项目时,将选择 Datelist 中的相同索引,然后我会将数据发送到日期时间编辑

我尝试使用 QAbstractItemmodel 模型->index(row,column); 和 createindex 但我不太了解语法所以我把它搞砸了

QModelIndex i = ui->TimeList->currentIndex(); //it gets the index when an item is clicked
ui->DateList->setcurrentIndex(i); //it sets the same index in the other QListView
ui->DateList->clearSelection();
ui->DateList->selectionModel()->select(i, QItemSelectionModel::Select); //This highlights the same index in other QListView and it works fine


QTime t = i.data(Qt::DisplayRole).toTime(); // It converts to QTime fine
i = ui->DateList->currentindex(); // i try to change the value of index to get the date
QDate d = i.data(Qt::DisplayRole).toDate(); 

ui->TimeEdit->setTime(t);
ui->DateEdit->setDate(d);

我收集到的是 i.data 输出对 QDate 无效,因为它在 qDebug 中如此说明。 所以我想索引不仅包含行和列值,而且如何将它分配给 Datelist 超出了我的范围。 (: 提前致谢

【问题讨论】:

相同的索引是什么意思?您是指在同一行中的项目还是显示相同文本的项目? @eyllanesc 位于同一行中的项目,以便如果在第一个列表中选择第 1 行,则将在第二个列表中选择第 1 行 【参考方案1】:

我只需要学习语法来创建一个新的 QIndexModel

QModelIndex i = ui->TimeList->currentIndex();
QModelIndex i2 = ui->DateList->model()->index(i.row(), 0);

所以我使用 index1 中的相同行值,但将其分配给第二个 QListview

【讨论】:

以上是关于如何将 QModelIndex 设置为 QListView的主要内容,如果未能解决你的问题,请参考以下文章

如何将 QModelIndex 与新行关联?

将 QList<std::string> 转换为 QList<QString>

将 QList 拆分为块、指针或引用?

C++ 继承 - QList

无法为“QModelIndex”获取“QWidget* 编辑器”

如何正确地将对象/指针存储到 Qlist 中