Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Adding pushButton on QFileDialog



  • Hi
    I tried to add a pushButton on QFileDialog by

    class FileDialog : public QFileDialog
    {
        QPushButton *pb;
    public:
        FileDialog(QWidget *parent) : QFileDialog(parent){}
    
        void addWidget()
        {
            QGridLayout* mainLayout = dynamic_cast <QGridLayout*>(this->layout());
            if( !mainLayout){
                qDebug()<<"mainLayout is NULL";
            }else{
    
                QHBoxLayout *hbl =new QHBoxLayout(0);
                pb =new QPushButton(QString("My checkbox"));
                hbl->addWidget(pb);
                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);
        fd->addWidget();
    

    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 http://doc.qt.io/qt-5/qobject.html#qobject_cast . Or just pass layout pointer as argument in your function.


  • Lifetime Qt Champion

    @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)
    {
        setOption(QFileDialog::DontUseNativeDialog);
    }
    


  • @mtrch
    Thank you mtrch, That makes it return QGridLayout correctly,
    but
    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->setAcceptMode(QFileDialog::AcceptOpen);
    fd->setDirectory("/home/jana");
    fd->setFileMode(QFileDialog::ExistingFile);
    fd->setViewMode(QFileDialog::Detail);
    fd->setNameFilter(tr("Image Files (*.png *.jpg *.bmp)"));
    if (!fd->exec())
    	//cancelled
    	return;
    fileName=fd->selectedFiles().first();
    

    -Michael.



  • @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