在QComboBox的基础上实现复选功能

这个是最近的一个项目上需要实现的功能。要求如下:

  1. 下拉列表的项目可以多选
  2. 显示框不能编辑
  3. 所选中的项目在显示框中出现

下面根据网上的提示代码(参照博客 一去二三里),主要实现如下代码(与参照略有不同):

实现方案:

QListWidget、QListWidgetItem、QComboBox

初始化控件及模拟数据填充:

 1     comboBox = new QComboBox(this); //初始化显示控件
 2 
 3     QHBoxLayout* mainLayout = new QHBoxLayout(this);
 4     mainLayout->addWidget(comboBox);
 5     setLayout(mainLayout);
 6 
 7     //初始化数据源
 8     listWidget = new QListWidget;
 9     for(int i = 0; i < 5; ++i)
10     {
11         QListWidgetItem* item = new QListWidgetItem(tr.("Item %1").arg(i));
12         item->setCheckState(Qt::Unchecked); //显示复选框
13 
14         listWidget->addItem(item);
15     }
16 
17    //默认选中第一个数据
18     QListWidgetItem* item = listWidget->item(0);
19     if(item)
20     {
21         item->setCheckState(Qt::Checked);
22     }
23 
24     //设置数据源到显示控件中
25     comboBox->setModel(listWidget->model());
26     comboBox->setView(listWidget);
27 
28     //设置只读编辑框
29     comboBox->setEditable(true);
30     QLineEdit* lineEdit = comboBox->lineEdit();
31     if(lineEdit)
32     {
33         lineEdit->setReadOnly(true);
34     }
35 
36     setMinimumWidth(200);
37 
38     //更新显示的内容
39     connect(comboBox, SIGNAL(currentIndexChanged(int)), this,         SLOT(onCurrentIndexChanged(int)));
View Code

更新显示内容的代码如下(需要在头文件中设置该函数为槽函数):

 1     //获取当前点击的对象
 2     QListWidgetItem* item = listWidget->item(index);
 3     if(!item)
 4         return ;
 5 
 6     //更新当前点击对象的选中状态
 7     if(item->checkState() == Qt::Unchecked)
 8     {
 9         item->setCheckState(Qt::Checked);
10     }
11     else
12     {
13         item->setCheckState(Qt::Unchecked);
14     }
15 
16     //循环获取所有选中状态的对象显示文字
17     QString text;
18     for(int row = 0, rows = listWidget->count(); row < rows; ++row)
19     {
20         QListWidgetItem* item = listWidget->item(row);
21         if(item && item->checkState() == Qt::Checked)
22         {
23             text.append(item->text() + ";");
24         }
25     }
26 
27     //更新显示控件的文字
28     comboBox->lineEdit()->setText(text.mid(0, text.size() - 1));
View Code

完整的实现代码,请点击 这里

MultiComboBox文件夹里包含所有的实现文件

转载于:https://www.cnblogs.com/zhugaopeng/p/8196499.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值