Qt提供了颜色选择框,如下图:
 
QColorDialog使用方法
例如下面的代码,点击按钮弹出颜色选择框,选择颜色,改变QLabel的背景色
#include "widget.h"
#include "ui_widget.h"
#include <QColorDialog>
#include <QPalette>
Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    ui->label->setText(u8"我是lable");
}
Widget::~Widget()
{
    delete ui;
}
void Widget::on_btn1_clicked()
{
    QColor color = QColorDialog::getColor(Qt::white, this, u8"选择颜色");
    if(color.isValid())
    {
        QPalette palette;
        palette.setColor(QPalette::Background ,color);
        ui->label->setAutoFillBackground(true);
        ui->label->setPalette(palette);
    }
}
 
效果如下:
 
getColor的调用
getColor声明如下:
static QColor getColor(const QColor &initial = Qt::white,
                           QWidget *parent = nullptr,
                           const QString &title = QString(),
                           ColorDialogOptions options = ColorDialogOptions());
 
第一个参数是默认的颜色,例如我在上面的代码中,直接设为白色
 第二个参数是父窗口指针
 第三个是颜色对话框窗口标题
QPalette setColor
setColor的声明如下:
inline void QPalette::setColor(ColorRole acr, const QColor &acolor)
 
可以使用QColorDialog返回的颜色直接构造QPalette,注意setColor的第一个参数需要一个ColorRole, 可以参看如下说明:
enum ColorRole { WindowText, Button, Light, Midlight, Dark, Mid,
                     Text, BrightText, ButtonText, Base, Window, Shadow,
                     Highlight, HighlightedText,
                     Link, LinkVisited,
                     AlternateBase,
                     NoRole,
                     ToolTipBase, ToolTipText,
                     PlaceholderText,
                     NColorRoles = PlaceholderText + 1,
#if QT_DEPRECATED_SINCE(5, 13)
                     Foreground Q_DECL_ENUMERATOR_DEPRECATED_X("Use QPalette::WindowText instead") = WindowText,
                     Background Q_DECL_ENUMERATOR_DEPRECATED_X("Use QPalette::Window instead") = Window
#endif
                   };
 
例如上面的代码是修改Label的背景颜色,那么就需要使用Background枚举体,如果改变文本就使用Text.










