How could I use the QColorDialog inside another widget not as a separate dialog?

balint.miklos picture balint.miklos · May 20, 2009 · Viewed 11.9k times · Source

I would like to use QColorDialog not as a dialog window but as a widget which I could insert into a layout. (More specifically as a custom sub menu in a context menu)

I looked into the QColorDialog sourcecode, and I could probably copy over a part of the internal implementation of the QColorDialog to achieve this, but is there a cleaner way to do this? I am using Qt 4.5.1...

Answer

Wiz picture Wiz · Jan 26, 2013

QColorDialog is a dialog which means IT IS a widget. All you need to do is set a few window flags and drop it into your layout as you wish. Here is a (tested) example:

#include <QApplication>
#include <QMainWindow>
#include <QColorDialog>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    /* setup a quick and dirty window */
    QMainWindow app;
    app.setGeometry(250, 250, 600, 400);

    QColorDialog *colorDialog = new QColorDialog(&app);
    /* set it as our widiget, you can add it to a layout or something */
    app.setCentralWidget(colorDialog);
    /* define it as a Qt::Widget (SubWindow would also work) instead of a dialog */
    colorDialog->setWindowFlags(Qt::Widget);
    /* a few options that we must set for it to work nicely */
    colorDialog->setOptions(
                /* do not use native dialog */
                QColorDialog::DontUseNativeDialog
                /* you don't need to set it, but if you don't set this
                    the "OK" and "Cancel" buttons will show up, I don't
                    think you'd want that. */
                | QColorDialog::NoButtons
    );

    app.show();
    return a.exec();
}