Qt提供了颜色选择框,如下图:
QColorDialog使用方法
例如下面的代码,点击按钮弹出颜色选择框,选择颜色,改变QLabel的背景色
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
|
#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声明如下:
1
2
3
4
|
static QColor getColor( const QColor &initial = Qt::white, QWidget *parent = nullptr, const QString &title = QString(), ColorDialogOptions options = ColorDialogOptions()); |
第一个参数是默认的颜色,例如我在上面的代码中,直接设为白色
第二个参数是父窗口指针
第三个是颜色对话框窗口标题
QPalette setColor
setColor的声明如下:
1
|
inline void QPalette::setColor(ColorRole acr, const QColor &acolor) |
可以使用QColorDialog返回的颜色直接构造QPalette,注意setColor的第一个参数需要一个ColorRole, 可以参看如下说明:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
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.
到此这篇关于C++ Qt QColorDialog使用方法的文章就介绍到这了,更多相关 Qt QColorDialog内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!
原文链接:https://blog.csdn.net/yao_hou/article/details/122512759