From Gossip@caterpillar

Qt3 Gossip: QColorDialog 類別

QColorDialog類別可以顯示一個顏色選取的對話方塊,使用者選取顏色之後,會傳回一個QColor物件,我們可以藉由這個QColor物件來取得所選取顏色的RGB值。

下面這個程式是QColorDialog的簡單的示範,我們在選取顏色之後,使用QMessageBox來顯示選取顏色的RGB值;請編輯main.cpp:
  • main.cpp
#include <qapplication.h>
#include <qmessagebox.h>
#include <qcolordialog.h>

int main(int argc, char **argv) {
QApplication app(argc, argv);

QColorDialog::setCustomColor(0, QRgb(0x0000FF));
QColor c = QColorDialog::getColor(QColor(0, 255, 0));
QString text;

if(c.isValid()) {
text.sprintf("R:%d G:%d B:%d", c.red(), c.green(), c.blue());
QMessageBox::information(0, "Get Selected Color",
text, "OK", "", "", 0, 1);
}

text.sprintf("%d custom colors available", QColorDialog::customCount());
QMessageBox::information(0, "Get Selected Color",
text, "OK", "", "", 0, 1);

return 1;
}

setCustomColor()方法設定顏色選取方塊中,自訂色彩中出現時預設的選取顏色;getColor()這個方法除了取回設定的顏色之外,也會 將顏色選取方塊的值預設為指定的值;customCount()方法可以取回自訂色彩的最大個數,預設是16個待定義色彩。

下圖為顏色選取方塊執行的畫面: