Adding pushButton on QFileDialog

  • Hi
    I tried to add a pushButton on QFileDialog by

    class FileDialog : public QFileDialog
        QPushButton *pb;
        FileDialog(QWidget *parent) : QFileDialog(parent){}
        void addWidget()
            QGridLayout* mainLayout = dynamic_cast <QGridLayout*>(this->layout());
            if( !mainLayout){
                qDebug()<<"mainLayout is NULL";
                QHBoxLayout *hbl =new QHBoxLayout(0);
                pb =new QPushButton(QString("My checkbox"));
                int num_rows = mainLayout->rowCount();
                qDebug()<<"num_rows: "<<num_rows;
                mainLayout->addLayout(hbl, num_rows, 0, 1, -1);
    When I executed
        FileDialog *fd=new FileDialog(this);

    I got the result,
    "mainLayout is NULL"
    It means I could not get the QGridLayout* by this->layout().
    Is it a bug? I use Qt 5.6.2 in windows7.

  • Try to use . Or just pass layout pointer as argument in your function.

  • Qt Champions 2018

    @samdol I guess the layout in a QFileDialog is not QGridLayout, that's why the cast fails.

  • This is because QFileDialog uses native file dialog by default, you just need to turn off this behavior:

    FileDialog(QWidget *parent) : QFileDialog(parent)

  • @mtrch
    Thank you mtrch, That makes it return QGridLayout correctly,
    fileName = fd->getOpenFileName(this,
    tr("Open Image"), "/home/jana", tr("Image Files (*.png *.jpg *.bmp)"));
    does not show any change on FileDialog.

  • getOpenFileName is a static function. It does not care about any changes you made to fd.

    You will have to do everything of the static function yourself:

    fd->setWindowTitle("Open Image");
    fd->setNameFilter(tr("Image Files (*.png *.jpg *.bmp)"));
    if (!fd->exec())


  • @m.sue
    Thanks. It works as expected. Can I set the style of fd to the style of the QFileDialog on executing getOpenFileName()?

  • "style": IIRC the static function uses the native dialog, by default. If you mean that, then no (see above).

Log in to reply

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.