2017-01-26 5 views
1

文字列値を指定してQtで抽象的なアイテムビューのアイテムを選択しようとしています。私はすでにそれが文字列の内容に基づいてQModelIndexを見つける関数を書いています。QAbstractItemViewでQModelIndexesをプログラムで選択

私は現在、それらをすべて単一の選択に見いだすことを試みています。QModelIndex私のメソッドシグネチャ:

// Will select all items that contain any of the strings 
    // given by 1st argument 
    virtual void selectItems(const QStringList&) override; 

私の実装では、このようになります(ただし、正常に動作しません):

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); 
    } 
} 

問題があるが、このコードは常に唯一例えば、リスト、内の最初の項目を選択します。 "B1","C1","A1"のためには、次のようになります。

image description

テーブルは複数選択が有効になっている:

image description

それでは、どのように私は適切にプログラムで複数の項目を選択しますか? findIndexByStringが必要な場合は、こちらをご覧ください: https://github.com/Darker/qt-gui-test/blob/master/results/QAbstractItemViewResult.cpp#L5

答えて

3

すべての繰り返しで選択をクリアします。

置き換え:

QItemSelectionModel::SelectionFlags flags = QItemSelectionModel::ClearAndSelect; 

によって:

QItemSelectionModel::SelectionFlags flags = QItemSelectionModel::Select; 

EDIT:あなたはtextの代わりにlist[0]を渡す:

findIndexByString(targetView_, list[0]) 
ところで210

、あなたのループ内でのconst参照を使用する必要があります。

Q_FOREACH(const QString &text, list) { 

またはネイティブバージョンを使用すると、C++ 11または優れたを使用している場合:

for (const QSring &text : list) { 
+0

フラグはありませんループで使用されます。 –

+0

あなたはそうです。私は私の答えを編集しました。 – rom1v

+0

ありがとうございます。主な問題はおそらく残りの 'list [0]'でした。ところで、 'ClearAndSelect'はうまくいきます。私は100%ではありませんが、「選択」だけで既存の選択肢に新しい選択肢が追加されると思います。 –

関連する問題