上周为了用Qt写一个类似颜色下拉框的东西,查阅了网上的多数相关资料,依然没有我想要的。终于在周四的时候下定决心重写QCombobox类来实现功能,现在把它贴出来,望看到的人,批评指正。废话不多说,先上图:
图片1-1
点击下拉之后,出现的是下拉表格,里面都是button,我用了最简单的setstylesheet直接设置背景,点击颜色按钮之后,我展示的效果是在编辑框位置有颜色label。因为没有创建这些按钮的索引,所以我是直接简单粗暴的用的按钮的cliced()信号,颜色的话我是重写了QPushButton类,发送的是clicked(QString),将颜色直接传过去的。other按钮是可以弹出QColorDialog,Qt自带的就不多说了。效果如图:
图片1-2
图片1-3
关键代码如下:
MyCombobox::MyCombobox(QWidget *parent) : QComboBox(parent)
{
QTableWidget * tableWidget = new QTableWidget(, );
tableWidget->verticalHeader()->setVisible(false);
tableWidget->horizontalHeader()->setVisible(false);
tableWidget->setShowGrid(false);
tableWidget->setSpan(,,,);
int k = ;
for (int i = ; i < ; ++i)
{
if(i==||i==){
for (int j = ; j < ; ++j)
{
tableWidget->setColumnWidth(j, );
tableWidget->setRowHeight(j, );
QStringList colorList = QColor::colorNames();\
MyPushButton * itemWidget = new MyPushButton(colorList[k],this);
itemWidget->setStyleSheet("QPushButton {">";}");
k++;
tableWidget->setCellWidget(i, j, itemWidget);
connect(itemWidget,SIGNAL(clicked(QString)),this,SLOT(change(QString)));
}
}else{
other =new QPushButton(this);
other->setText("other");
tableWidget->setCellWidget(, , other);
}
}
connect(other,SIGNAL(clicked()),this,SLOT(otherColor()));
this->setModel(tableWidget->model());
this->setView(tableWidget);
}
void MyCombobox::change(QString colorname)
{
QLabel *showColor = new QLabel(this);
showColor->setStyleSheet("QLabel {">";}");
showColor->setGeometry(,,,);
showColor->setVisible(true);
}
void MyCombobox::otherColor()
{
QColor mycolor = QColorDialog::getColor(Qt::white, this);
this->change(mycolor.name());
}
刚接触Qt,写的不好,如果各位有好的想法,我们可以多多沟通,比心