[英]Programmatically select QModelIndexes in QAbstractItemView
I am trying to select items of abstract item view in Qt given their string values. 我试图在Qt中选择抽象项目视图中的项目,给出它们的字符串值。 I have already written function that finds any
QModelIndex
based on it's string content. 我已经编写了函数,可以根据它的字符串内容找到任何
QModelIndex
。
I am now trying to put all those QModelIndex
es that I find into single selection. 我现在正试图将我发现的所有
QModelIndex
es放入单选。 My method signature: 我的方法签名:
// Will select all items that contain any of the strings
// given by 1st argument
virtual void selectItems(const QStringList&) override;
My implementation looks like this (but doesn't work properly): 我的实现看起来像这样(但不能正常工作):
void QAbstractItemViewResult::selectItems(const QStringList& list)
{
if(list.size() > 0) {
QItemSelectionModel::SelectionFlags flags = QItemSelectionModel::ClearAndSelect;
QItemSelection selection;
Q_FOREACH(const QString text, list) {
// Find index by string is a method I implemented earlier
// The method works correctly
QModelIndex index(findIndexByString(targetView_, list[0]));
if(index.isValid()) {
// This is an attempt to add model indx into selection
selection.select(index, index);
}
}
// When the selection is created, this should select it in index
targetView_->selectionModel()->select(selection, flags);
}
}
Problem is, this code always only selects first item in the list, eg. 问题是,这段代码总是只选择列表中的第一项,例如。 for
"B1","C1","A1"
it looks like this: 对于
"B1","C1","A1"
它看起来像这样:
The table has multi selection enabled: 该表启用了多选:
So how do I properly select multiple items programmatically? 那么如何以编程方式正确选择多个项目? If you need the
findIndexByString
, it can be found here: https://github.com/Darker/qt-gui-test/blob/master/results/QAbstractItemViewResult.cpp#L5 如果你需要
findIndexByString
,可以在这里找到它: https : //github.com/Darker/qt-gui-test/blob/master/results/QAbstractItemViewResult.cpp#L5
You clear the selection on every iteration. 您清除每次迭代的选择。
Replace: 更换:
QItemSelectionModel::SelectionFlags flags = QItemSelectionModel::ClearAndSelect;
by: 通过:
QItemSelectionModel::SelectionFlags flags = QItemSelectionModel::Select;
EDIT: You pass list[0]
instead of text
: 编辑:您传递
list[0]
而不是text
:
findIndexByString(targetView_, list[0])
By the way, you should use a const reference in your loop: 顺便说一下,你应该在循环中使用const引用 :
Q_FOREACH(const QString &text, list) {
Or the native version if you use C++11 or superior: 或者如果您使用C ++ 11或更高版本,则使用本机版本:
for (const QSring &text : list) {
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.