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

How to hide a QPushButton in a QToolBar?



  • Hello,

    I am trying to hide a QPushButton but it does not work.
    Here is the part of my code with the very basic for this purpose, pressing button1 should hide button2...

    mainwindow.h

    #ifndef MAINWINDOW_H
    #define MAINWINDOW_H
    
    #include <QMainWindow>
    class QToolBar;
    class QPushButton;
    
    class MainWindow : public QMainWindow
    {
        Q_OBJECT
    
    public:
        MainWindow(QWidget *parent = 0);
    
    private:
        QToolBar*       m_toolBar;
        QPushButton*    m_button1;
        QPushButton*    m_button2;
    
    private slots:
        void            Button1Slot();
    
    };
    
    #endif // MAINWINDOW_H
    

    mainwindow.cpp

    MainWindow::MainWindow(QWidget *parent)
        : QMainWindow(parent)
    {
        m_toolBar = addToolBar(QString("test"));
    
        m_button1 = new QPushButton(QString("Button 1"), m_toolBar);
        m_toolBar->addWidget(m_button1);
        //m_button1->show(); //Does not change anything
        QObject::connect(m_button1, SIGNAL(clicked(bool)), this, SLOT(Button1Slot()));
    
        m_button2 = new QPushButton(QString("Button 2"), m_toolBar);
        //m_button2->show(); //Does not change anything
        m_toolBar->addWidget(m_button2);
    }
    
    void MainWindow::Button1Slot()
    {
        m_button2->hide();              // Does not work
        m_button2->setHidden(true);     // Does not work
        m_button2->setVisible(false);   // Does not work
    }
    

    main.cpp

    #include "mainwindow.h"
    #include <QApplication>
    
    int main(int argc, char *argv[])
    {
        QApplication a(argc, argv);
        MainWindow w;
        w.show();
    
        return a.exec();
    }
    

    Thanks for your help.



  • @Calivernon

    Hi doc says
    You should use QAction::setVisible() to change the visibility of the widget. Using QWidget::setVisible(), QWidget::show() and QWidget::hide() does not work.

    Example here.



  • Thank you Ratzz,

    that is perfect!


Log in to reply