在Qt编程中,需要设置字体或背景的颜色,但又无法直接写出颜色值。本文则总结Qt所能识别的所有的颜色,并提供颜色的十六进制数值和RGB数值。
(1)colorlist.h
#ifndef COLORLIST_H #define COLORLIST_H #include <QtGui> #include "colorlisteditor.h" class ColorList : public QWidget { Q_OBJECT public: ColorList(QWidget *parent = 0); ~ColorList(); private slots: void slotActivated(const QString & text); private: ColorListEditor *colorList; QLabel *colorIco; QLabel *colorText; QLabel *rgbText; }; #endif // COLORLIST_H(2)colorlist.cpp
#include "colorlist.h" ColorList::ColorList(QWidget *parent) : QWidget(parent, Qt::WindowCloseButtonHint) { colorList = new ColorListEditor(this); colorList->move(70, 40); connect(colorList, SIGNAL(activated(QString)), this, SLOT(slotActivated(QString))); colorIco = new QLabel(this); colorIco->setGeometry(95, 70, 120, 120); colorText = new QLabel(this); colorText->setStyleSheet("color:#FF0000;background:#999999"); colorText->setAlignment(Qt::AlignCenter); colorText->setGeometry(115, 200, 80, 25); rgbText = new QLabel(this); rgbText->setStyleSheet("color:#FF0000;background:#999999"); rgbText->setAlignment(Qt::AlignCenter); rgbText->setGeometry(10, 230, 280, 25); slotActivated(colorList->currentText()); resize(300, 300); move((QApplication::desktop()->width() - width())/2, (QApplication::desktop()->height() - height())/2); } ColorList::~ColorList() { } void ColorList::slotActivated(const QString &text) { QString colorName = colorList->color().name().toUpper(); colorIco->setStyleSheet(QString("background:%1").arg(colorName)); colorText->setText(colorName); rgbText->setText(tr("Red:%1 Green:%2 Blue:%3 Alpha:%4").arg(colorList->color().red()).arg(colorList->color().green()) .arg(colorList->color().blue()).arg(colorList->color().alpha())); }(3)colorlisteditor.h
#ifndef COLORLISTEDITOR_H #define COLORLISTEDITOR_H #include <QComboBox> QT_BEGIN_NAMESPACE class QColor; class QWidget; QT_END_NAMESPACE //! [0] class ColorListEditor : public QComboBox { Q_OBJECT Q_PROPERTY(QColor color READ color WRITE setColor USER true) public: ColorListEditor(QWidget *widget = 0); public: QColor color() const; void setColor(QColor c); private: void populateList(); }; //! [0] #endif(4)colorlisteditor.cpp
#include <QtGui> #include "colorlisteditor.h" ColorListEditor::ColorListEditor(QWidget *widget) : QComboBox(widget) { populateList(); } //! [0] QColor ColorListEditor::color() const { return qVariantValue<QColor>(itemData(currentIndex(), Qt::DecorationRole)); } //! [0] //! [1] void ColorListEditor::setColor(QColor color) { setCurrentIndex(findData(color, int(Qt::DecorationRole))); } //! [1] //! [2] void ColorListEditor::populateList() { QStringList colorNames = QColor::colorNames(); for (int i = 0; i < colorNames.size(); ++i) { QColor color(colorNames[i]); insertItem(i, colorNames[i]); setItemData(i, color, Qt::DecorationRole); } } //! [2](5)main.cpp
#include "colorlist.h" #include <QApplication> int main(int argc, char *argv[]) { QApplication a(argc, argv); ColorList w; w.show(); return a.exec(); }(6)运行
其中有148种颜色值可以供自己选择。