Qt顏色下拉框


  上周為了用Qt寫一個類似顏色下拉框的東西,查閱了網上的多數相關資料,依然沒有我想要的。終於在周四的時候下定決心重寫QCombobox類來實現功能,現在把它貼出來,望看到的人,批評指正。廢話不多說,先上圖:

       

                                       圖片1-1

  點擊下拉之后,出現的是下拉表格,里面都是button,我用了最簡單的setstylesheet直接設置背景,點擊顏色按鈕之后,我展示的效果是在編輯框位置有顏色label。因為沒有創建這些按鈕的索引,所以我是直接簡單粗暴的用的按鈕的cliced()信號,顏色的話我是重寫了QPushButton類,發送的是clicked(QString),將顏色直接傳過去的。other按鈕是可以彈出QColorDialog,Qt自帶的就不多說了。效果如圖:

        圖片1-2

                                 圖片1-3

關鍵代碼如下:

 1 MyCombobox::MyCombobox(QWidget *parent) : QComboBox(parent)
 2 {
 3     QTableWidget * tableWidget = new QTableWidget(3, 8);
 4     tableWidget->verticalHeader()->setVisible(false);
 5     tableWidget->horizontalHeader()->setVisible(false);
 6     tableWidget->setShowGrid(false);
 7     tableWidget->setSpan(2,0,1,8);
 8     int k = 0;
 9     for (int i = 0; i < 3; ++i)
10     {
11         if(i==0||i==1){
12             for (int j = 0; j < 8; ++j)
13                 {
14                     tableWidget->setColumnWidth(j, 32);
15                     tableWidget->setRowHeight(j, 24);
16                     QStringList colorList = QColor::colorNames();\
17                     MyPushButton * itemWidget = new MyPushButton(colorList[k],this);
18                     itemWidget->setStyleSheet("QPushButton {">";}");
19                     k++;
20                     tableWidget->setCellWidget(i, j, itemWidget);
21                     connect(itemWidget,SIGNAL(clicked(QString)),this,SLOT(change(QString)));
22             }
23         }else{
24             other =new QPushButton(this);
25             other->setText("other");
26             tableWidget->setCellWidget(2, 0, other);
27         }
28      }
29     connect(other,SIGNAL(clicked()),this,SLOT(otherColor()));
30     this->setModel(tableWidget->model());
31     this->setView(tableWidget);
32 }
33 void MyCombobox::change(QString colorname)
34 {
35     QLabel *showColor = new QLabel(this);
36     showColor->setStyleSheet("QLabel {">";}");
37     showColor->setGeometry(5,5,240,20);
38     showColor->setVisible(true);
39 }
40 void MyCombobox::otherColor()
41 {
42    QColor mycolor = QColorDialog::getColor(Qt::white, this);
43    this->change(mycolor.name());
44 }

  剛接觸Qt,寫的不好,如果各位有好的想法,我們可以多多溝通,比心


免責聲明!

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



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