最近在做一個項目,需要把客戶端界面的顏色改變成為客戶需要的顏色,但蓋起來相當(dāng)麻煩,于是就想到QColorDialog來拾取顏色,動態(tài)的改變界面的顏色,但是這種方法只適用客戶端開始設(shè)計的時候就隨之引入。下面是代碼:
Widget.h
#ifndef WIDGET_H#define WIDGET_H#include <QWidget>#include <QColorDialog>namespace Ui {class Widget;}class Widget : public QWidget{ Q_OBJECTpublic: 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); //獲取當(dāng)前窗口的背景色 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)));//顯示當(dāng)前選中顏色的效果 connect(m_pColor,SIGNAL(colorSelected(QColor)),this,SLOT(SetColor(QColor)));//OK信號連接 //rejected信號會在QColorDialog框關(guān)閉或按Cancel按鈕時發(fā)出,可通過綁定該信號來進(jìn)行Cancel信號過濾 connect(m_pColor,SIGNAL(rejected()),this,SLOT(SetColor_1()));}