在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文件夾里包含所有的實現文件


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM