顏色對話框(QColorDialog)

QColorDialog為一個選取顏色的對話方塊,來讓使用者選取顏色,供程式後續使用,範例建立一個QPushButton和一個QFrame,當使用者點擊按鍵,這時會跳出顏色對話框,我們從顏色對話框選擇顏色,這時QFrame背景會變成所選擇的顏色。


dialog.h

#ifndef DIALOG_H
#define DIALOG_H

#include <QDialog>
#include <QFrame>
#include <QVBoxLayout>
#include <QPushButton>

class Dialog : public QDialog
{
    Q_OBJECT

public:
    Dialog(QWidget *parent = 0);
private:
    QPushButton *colorBtn;
    QFrame *colorFrame;
    QVBoxLayout *mainLayout;
private slots:
    void showColor();
};

#endif 

dialog.cpp

#include "dialog.h"
#include<QColorDialog>

Dialog::Dialog(QWidget *parent) : 
    QDialog(parent)
{
    setWindowTitle(QStringLiteral("顏色對話框"));
    colorBtn = new QPushButton;
    colorBtn->setText(QStringLiteral("開啟顏色對話框"));
    colorFrame = new QFrame;
    colorFrame->setFrameShape(QFrame::Box);
    colorFrame->setAutoFillBackground(true);
    mainLayout = new QVBoxLayout(this);
    mainLayout->addWidget(colorBtn);
    mainLayout->addWidget(colorFrame);
    connect(colorBtn,SIGNAL(clicked()),this,SLOT(showColor()));
}

void Dialog::showColor(){
    QColor c = QColorDialog::getColor(Qt::blue);
    if(c.isValid()){
        colorFrame->setPalette(QPalette(c));
    }
}

main.cpp

#include "dialog.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    Dialog w;
    w.resize(100,70);
    w.show();

    return a.exec();
}

QColorDialog

QColorDialog