1

リストビューにチェックボックス項目を追加しています。

次に、チェック ボックス インジケーターを変更すると、項目行が選択されません。また、リスト内の項目を選択しても、チェック ボックス インジケーターは変化しません。

チェックボックス インジケーターは項目選択行で選択/選択解除する必要があり、チェックボックス インジケーターの選択は選択された項目行を設定する必要があります。

リスト ビューの初期化:

QListView *poListView = new QListView(this);

// Create list view item model
QStandardItemModel*  poModel =
          new QStandardItemModel(poListView);

QStandardItem *poListItem = new QStandardItem;

// Checkable item
poListItem->setCheckable( true );

// Uncheck the item
poListItem->setCheckState(Qt::Unchecked);

// Save checke state
poListItem->setData(Qt::Unchecked, Qt::CheckStateRole);

poModel->setItem(0, poListItem);

poListView->setModel(poModel);

なにか提案を ?

4

2 に答える 2

1

itemChangedの信号を接続しQStandardItemModel、そこで項目を手動で選択する必要があります。

選択時にチェックボックスをオンにしたい場合は、selectionChanged信号を接続しQListView::selectionModel()、そこで項目をチェック/チェック解除する必要があります。

また、手動で設定する必要はありませんQt::CheckStageRole

C++11 とラムダを使用すると、次のようになります。

connect(poModel, &QStandardItemModel::itemChanged, [poListView, poModel](QStandardItem * item) {
    const QModelIndex index = poModel->indexFromItem(item);
    QItemSelectionModel *selModel = poListView->selectionModel();
    selModel->select(QItemSelection(index, index), item->checkState() == Qt::Checked ? QItemSelectionModel::Select : QItemSelectionModel::Deselect);
});

connect(poListView->selectionModel(), &QItemSelectionModel::selectionChanged, [poModel](const QItemSelection &selected, const QItemSelection &deselected) {
    for (const QModelIndex &index : selected.indexes()) {
        poModel->itemFromIndex(index)->setCheckState(Qt::Checked);
    }
    for (const QModelIndex &index : deselected.indexes()) {
        poModel->itemFromIndex(index)->setCheckState(Qt::Unchecked);
    }
});

または古いconnect構文で:

void MyClass::handleCheckedChanged(QStandardItem *item) {
    const QModelIndex index = item->model()->indexFromItem(item);
    QItemSelectionModel *selModel = poListView->selectionModel();
    selModel->select(QItemSelection(index, index), item->checkState() == Qt::Checked ? QItemSelectionModel::Select : QItemSelectionModel::Deselect);
}

void MyClass::handleSelectionChanged(const QItemSelection &selected, const QItemSelection &deselected) {
    foreach (const QModelIndex &index, selected.indexes()) {
        index.model()->itemFromIndex(index)->setCheckState(Qt::Checked);
    }
    foreach (const QModelIndex &index, deselected.indexes()) {
        index.model()->itemFromIndex(index)->setCheckState(Qt::Unchecked);
    }
}

...

connect(poModel, SIGNAL(itemChanged(QStandardItem *)), this, SLOT(handleCheckedChanged(QStandardItem *)));

connect(poListView->selectionModel(), SIGNAL(selectionChanged(QItemSelection, QItemSelection)), this, SLOT(handleSelectionChanged(QItemSelection, QItemSelection)));
于 2015-07-01T15:16:58.340 に答える