當我選擇/取消選擇他們父母的物品QCheckBox時,我想選擇/取消選擇所有孩子的物品QCheckBoxs。如何在QTreeView中選擇孩子的物品複選框
我繼承QTreeView並檢測QCheckBox何時被選中,然後我調用函數做選擇/取消選擇過程。
這裏我的代碼:
#ifndef MYQTREEVIEW_H
#define MYQTREEVIEW_H
#include <QTreeView>
#include <QMouseEvent>
#include <QDebug>
#include <QStandardItem>
class MyQTreeView: public QTreeView {
public:
MyQTreeView(QWidget* parent=0): QTreeView(parent){}
virtual ~MyQTreeView() {}
protected:
void resettingCheckBox (QModelIndex& parentIndex) {
if (! parentIndex.isValid())
return;
QString text = parentIndex.data(Qt::DisplayRole).value<QString>();
qDebug() << "parent is: " << text;
if (model()->hasChildren(parentIndex)) {
for(int i = 0; i < model()->rowCount(parentIndex) ; i++) {
QModelIndex childIndex = model()->index(i, 0, parentIndex);
if (model()->hasChildren(childIndex))
resettingCheckBox(childIndex);
else {
QString text = childIndex.data(Qt::DisplayRole).value<QString>();
qDebug() << "child is: " << text;
QStandardItem *parentItem = static_cast<QStandardItem*> (parentIndex.internalPointer());
QStandardItem *childItem = static_cast<QStandardItem*> (childIndex.internalPointer());
if (parentItem->checkState() == Qt::Checked) {
qDebug() << "child item " << childItem->checkState();
childItem->setCheckState(Qt::Unchecked);
}
else {
qDebug() << "child item " << childItem->checkState();
childItem->setCheckState( Qt::Checked);
}
}
}
}
}
void mousePressEvent (QMouseEvent *event) {
QModelIndex index = indexAt(event->pos());
if(index.isValid()) {
QStyleOptionButton opt;
opt.QStyleOption::operator=(viewOptions());
opt.rect = visualRect(index);
QRect rect = style()->subElementRect(QStyle::SE_ViewItemCheckIndicator, &opt);
if (rect.contains(event->pos())) {
resettingCheckBox(index);
}
QTreeView::mousePressEvent(event);
}
}
};
#endif // MYQTREEVIEW_H
代碼可能不工作時,我選擇/取消選擇父複選框(subchilds未選中/未選中)。
在此先感謝。
謝謝,它現在的工作。 – 2011-02-28 05:44:40