参考原文链接:
效果:
在原文链接的基础上补充的代码如下:
<全选功能>
//全选
MultiSelectComboBox.h
QCheckBox* checkAll;
MultiSelectComboBox.cpp
MultiSelectComboBox::MultiSelectComboBox(QWidget *parent)
: QComboBox {parent}
{
//设置全选框
checkAll=new QCheckBox();
QListWidgetItem* currentItem = new QListWidgetItem(list_widget_);
checkAll->setText("全选");
list_widget_->addItem(currentItem);
list_widget_->setItemWidget(currentItem, checkAll);
//全选 信号和槽
connect(checkAll, &QCheckBox::released, [=]() mutable {
bool ischecked = checkAll->isChecked();
for (int i = 0; i < list_widget_->count(); i++) {
QCheckBox *check_box =
static_cast<QCheckBox *>(list_widget_->itemWidget(list_widget_->item(i)));
check_box->setChecked(ischecked);
}
});
}
//单项与全选状态
void MultiSelectComboBox::checkAllState(int state)
{
if (Qt::Unchecked == state)
{
checkAll->setChecked(false);
}
else if (Qt::Checked == state)
{
bool isallcheck = true;
for (int i = 1; i < list_widget_->count(); i++)
{
QCheckBox *check_box = static_cast<QCheckBox*>(list_widget_->itemWidget(list_widget_->item(i)));
if(check_box->isChecked() == false)
{
isallcheck = false;
}
}
checkAll->setChecked(isallcheck);
}
}
//在创造出下拉框checkbox处连接单项与全选状态的信号和槽
void MultiSelectComboBox::addItem(const QString &_text, const QVariant &_variant /*= QVariant()*/)
{
Q_UNUSED(_variant);
QListWidgetItem *item = new QListWidgetItem(list_widget_);
QCheckBox *checkbox = new QCheckBox(this);
checkbox->setText(_text);
list_widget_->addItem(item);
list_widget_->setItemWidget(item, checkbox);
connect(checkbox, &QCheckBox::stateChanged, this, &MultiSelectComboBox::stateChange);
//单项与全选状态的信号和槽
connect(checkbox,&QCheckBox::stateChanged,this,&MultiSelectComboBox::checkAllState);
}
使用:
1.将QComboBox控件提升为该MultiSelectComboBox类
2.在QComboBox中加入QcheckbBox
参考原博主写好的函数直接用就可以了
资源: