class ColorButton : public QToolButton{ Q_OBJECTpublic: ColorButton(QWidget *parent = 0); void addColor(const QColor color, const QString text);public slots: void сolorClicked();private: QColor m_color;};
ColorButton::ColorButton(QWidget *parent) : QToolButton(parent){ m_color = Qt::black; QPixmap pixmap(size()); pixmap.fill(m_color); QIcon icon; icon.addPixmap(pixmap); setIcon(icon); connect(this, SIGNAL(clicked(bool)), this, SLOT(сolorClicked()));}void ColorButton::сolorClicked(){ QColor color = QColorDialog::getColor(m_color); if(color.isValid()){ m_color = color; QSize sz = size(); QPixmap pixmap(16,16); pixmap.fill(color); QIcon icon; icon.addPixmap(pixmap); setIcon(icon); }}
QApplication app(argc, argv); ColorButton test; test.setWindowTitle(QObject::tr("test")); test.show(); return app.exec();
C++ (Qt)#include <QtGui>#include "dialog.h" Dialog::Dialog(QWidget *parent) : QDialog(parent){ colorLabel = new QLabel; colorButton = new QPushButton(); connect(colorButton, SIGNAL(clicked()), this, SLOT(setColor())); QGridLayout *layout = new QGridLayout; layout->setColumnStretch(1, 1); layout->setColumnMinimumWidth(1, 250); layout->addWidget(colorButton, 0, 0); layout->addWidget(colorLabel, 0, 1); setLayout(layout); setWindowTitle(tr("Standard Dialogs"));} void Dialog::setColor(){ QColor color = QColorDialog::getColor(Qt::green, this); if (color.isValid()) { colorLabel->setText(color.name()); QPalette palette = colorButton->palette(); palette.setColor(QPalette::Button,color); colorButton->setPalette(palette); colorButton->setAutoFillBackground(true); }}