QCheckBox的三态复选框和反选

QCheckBox的三态复选框以及反选

在使用这个控件的时候,需求有可能是:点击复选框实线反选,并且选中项目的时候需要显示未选中、部分选中和全选。在这个需求当中,首先想到的是直接启用三态复选框,但是点击的时候就变成了可以点三次,这就和反选冲突了。

1.QCheckBox的三种状态:

1
2
3
4
5
enum CheckState {
Unchecked,
PartiallyChecked,
Checked
};

2.如何启用三态复选框

使用setTristate(true)即可开启,使用void QCheckBox::setCheckState(Qt::CheckState state)参数为Qt::PartiallyChecked也会启用三态

3.如何实现需求

显示选中状态:选择项目的时候根据选中情况设置QCheckBox的状态(如在QListView中可以通过QItemSelectionModel::selectionChanged信号实时统计)

1
2
3
4
5
6
7
8
9
10
11
12
if (selectedItems == 0)
{
ui->checkBox_select->setCheckState(Qt::Unchecked);
}
else if (selectedItems < totalItems)
{
ui->checkBox_select->setCheckState(Qt::PartiallyChecked);
}
else
{
ui->checkBox_select->setCheckState(Qt::Checked);
}

反选:点击checkBox后关掉三态,当你再次触发selectionChanged时三态复选框重新启用,即可实现实时选中及反选功能

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
connect(ui->checkBox_select, &QCheckBox::clicked, this, &MainWindow::selectAll);
void PhoneToPCPage::selectAll()
{
ui->checkBox_select->setTristate(false);
QListView* listView = getListView();
if (listView == nullptr)
{
return;
}
QItemSelectionModel* selectionModel = listView->selectionModel();
QAbstractItemModel* model = listView->model();
bool selectAll = ui->checkBox_select->checkState() == Qt::Checked;
if (selectAll) {
QItemSelection selection;
for (int row = 0; row < model->rowCount(); ++row) {
QModelIndex index = model->index(row, 0);
selection.select(index, index);
}
selectionModel->select(selection, QItemSelectionModel::Select);
}
else {
selectionModel->clearSelection();
}
}

3.效果图