私はこれが何度も尋ねられたことは知っていますが、関連するものは何も見つからないようです。QTreeViewのチェックボックス
Qtでパッケージ化されたthe simpletreemodel tutorialを使用すると、どのようにチェックボックスを追加できますか?
私はこれが何度も尋ねられたことは知っていますが、関連するものは何も見つからないようです。QTreeViewのチェックボックス
Qtでパッケージ化されたthe simpletreemodel tutorialを使用すると、どのようにチェックボックスを追加できますか?
まず、あなたがチェック状態を追跡するためにツリー項目を変更する必要があります:
private:
...
bool checked;
とセッターとゲッター:
bool isChecked() const { return checked; }
void setChecked(bool set) { checked = set; }
今モデルはそれほど変更する必要がありますビューがチェック状態を認識していることを確認します。
QVariant TreeModel::data(const QModelIndex &index, int role) const
{
if (!index.isValid())
return QVariant();
TreeItem *item = static_cast<TreeItem*>(index.internalPointer());
if (role == Qt::CheckStateRole && index.column() == 0)
return static_cast<int>(item->isChecked() ? Qt::Checked : Qt::Unchecked);
if (role != Qt::DisplayRole)
return QVariant();
return item->data(index.column());
}
モデルのフラグメソッドを変更してビューにはチェック可能なアイテムが含まれていることがわかります:
Qt::ItemFlags TreeModel::flags(const QModelIndex &index) const
{
if (!index.isValid())
return 0;
Qt::ItemFlags flags = Qt::ItemIsEnabled | Qt::ItemIsSelectable;
if (index.column() == 0)
flags |= Qt::ItemIsUserCheckable;
return flags;
}
私はこれを行うべきだと思います。ユーザーが項目をチェックしてアンピックしたときにTreeItemチェック状態を更新できるようにするには、TreeModelにQAbstractItemModel :: setDataメソッドを提供する必要があります。
私は自分自身の目的のために上記をPyQtに変換し、私は共有すると考えました。ここで
def data(self, index, role):
if not index.isValid():
return None
item = index.internalPointer();
if role == Qt.CheckStateRole and index.column() == self.check_col:
return int(Qt.Checked if item.isChecked() else Qt.Unchecked)
return super(TreeModel, self).data(index, role)
def flags(self, index):
if not index.isValid():
return None
if index.column() == self.check_col:
flags = Qt.ItemIsEnabled | Qt.ItemIsSelectable | Qt.ItemIsUserCheckable
else:
flags = super(TreeModel, self).flags(index)
return flags
def setData(self, index, value, role=Qt.EditRole):
if index.column() == self.check_col:
if role == Qt.EditRole:
return False
if role == Qt.CheckStateRole:
item = self.getItem(index)
item.setChecked(value)
self.dataChanged.emit(index, index)
return True
return super(TreeModel, self).setData(index, value, role)
古いスレッドですが、クラス全体を共有する可能性はありますか? – atomSmasher
はQStandardItemModel
を使用して別のPyQtは完全なウォーキングの例である:
model = QStandardItemModel()
parent_item = model.invisibleRootItem() # type: QStandardItem
for row in [
(Qt.Unchecked, 'unchecked'),
(Qt.PartiallyChecked, 'partially'),
(Qt.Checked, 'checked')
]:
checked, text = row
check_item = QStandardItem('')
check_item.setCheckable(True)
check_item.setCheckState(checked)
parent_item.appendRow([check_item, QStandardItem(text)])
treeview.setModel(model)
ところで、これはまた、任意のC++アプリケーションのために働く必要があります。
非常にクール!まさに私が探していたもの。しかし、私が構築しようとしているものに対してTreeWidgetを使用していたはずであることがわかった。しかし、ポストのために本当にありがとう。 – Drise
私はより良い解決策を提案することはできませんが、ブール値にはもちろん素晴らしいTRISTATENESSがありません。 (部分的に選択されたフォルダの場合) – eMPee584