使用QColorDialog颜色编辑选取对话框来拾取颜色,来动态改变界面整体的颜色风格,简单实例

最近在做一个项目,需要把客户端界面的颜色改变成为客户需要的颜色,但盖起来相当麻烦,于是就想到QColorDialog来拾取颜色,动态的改变界面的颜色,但是这种方法只适用客户端开始设计的时候就随之引入。下面是代码:

Widget.h

#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>
#include <QColorDialog>

namespace Ui {
class Widget;
}

class Widget : public QWidget
{
    Q_OBJECT

public:
    explicit Widget(QWidget *parent = 0);
    ~Widget();

private slots:
    void ShowColor(QColor);
    void SetColor(QColor);
    void SetColor_1();
    void on_pushButton_clicked();

private:
    Ui::Widget *ui;
    QColor m_color;//记录界面初始颜色
    QColor m_selectedColor;//记录按OK键后选中的颜色
};

#endif // WIDGET_H

Widget.cpp

#include "widget.h"
#include "ui_widget.h"
#include <QPalette>
#include <QDebug>

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);

    //获取当前窗口的背景色
    QPalette p = this->palette();
    QBrush brush = p.background();
    m_color = brush.color();
}

Widget::~Widget()
{
    delete ui;
}

void Widget::ShowColor(QColor color)
{
    QPalette palette;
    palette = this->palette();
    palette.setBrush(QPalette::Window,QBrush(color));
    this->setAutoFillBackground(true);
    this->setPalette(palette);
}

void Widget::SetColor(QColor color)
{
    if(color.isValid())
    {
        qDebug()<<"SetColor";
        QPalette palette;
        palette = this->palette();
        palette.setBrush(QPalette::Window,QBrush(color));
        this->setAutoFillBackground(true);
        this->setPalette(palette);
        m_selectedColor = color;
    }
}

void Widget::SetColor_1()
{

    if(m_selectedColor.isValid())
    {
        qDebug()<<"SetColor_1";
        QPalette palette;
        palette = this->palette();
        palette.setBrush(QPalette::Window,QBrush(m_selectedColor));
        this->setAutoFillBackground(true);
        this->setPalette(palette);
        m_color = m_selectedColor;
    }
    else
    {
        qDebug()<<"SetColor_2";
        QPalette palette;
        palette = this->palette();
        palette.setBrush(QPalette::Window,QBrush(m_color));
        this->setAutoFillBackground(true);
        this->setPalette(palette);
    }
}

void Widget::on_pushButton_clicked()
{
    QColorDialog *m_pColor = new QColorDialog(this);
    m_pColor->setCurrentColor(m_color);
    m_pColor->show();
    connect(m_pColor,SIGNAL(currentColorChanged(QColor)),this,SLOT(ShowColor(QColor)));//显示当前选中颜色的效果
    connect(m_pColor,SIGNAL(colorSelected(QColor)),this,SLOT(SetColor(QColor)));//OK信号连接
    //rejected信号会在QColorDialog框关闭或按Cancel按钮时发出,可通过绑定该信号来进行Cancel信号过滤
    connect(m_pColor,SIGNAL(rejected()),this,SLOT(SetColor_1()));
}

效果如下

这里写图片描述

猜你喜欢

转载自blog.csdn.net/qq_36391817/article/details/80706603