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

How to add different widgets in same position inQGridLayout



  • Hi,
    I am making a Qt widget application having following wigets: button1, button2, label1, label2.
    I have a QGridLayout having two rows.
    In row 1 I have button1 and button2. Now if button1 is clicked then label1 is displayed in row2 and if button2 is clicked label2 is displayed in row2.

    Here is my code:
    @
    {
    QPushButton *btn1=new QPushButton("click1");
    connect(btn, SIGNAL(clicked()), this, SLOT(disp1()));

    QPushButton *btn2=new QPushButton("click2");
    connect(btn1, SIGNAL(clicked()), this, SLOT(disp2()));
    
    gd=new QGridLayout();
    gd->addWidget(btn1,0,0);
    gd->addWidget(btn2,0,1);
    
    parent->setLayout(gd);
    

    }

    void MainWindow::disp1()
    {

    QLabel *lb1=new QLabel("label1");   
    gd->addWidget(lb1,1,0);
    

    }

    void MainWindow::disp2()
    {

       QLabel *lb2=new QLabel("label2"); 
       gd->addWidget(lb2,1,0);
    

    }
    @

    Whats happening is label1 and label2 are getting overlapped but i want to display only one at a time.
    I have also tried adding label1 and label2 to QFrame and then using frame1->hide() and frame2->hide() but some flickering of screen is there and a warnig is also displayed "Attempting to add QLayout to QFrame , which already has a layout"

    Kindly help.

    Thanks

    [edit: code tags added, koahnig]



  • "Please use code wrapping tags.":http://qt-project.org/wiki/ForumHelp#e3f82045ad0f480d3fb9e0ac2d58fb01

    I see two different possibilities either using "replaceWidget":http://qt-project.org/doc/qt-5/qlayout.html#replaceWidget or use "setVisible(false)":http://qt-project.org/doc/qt-5/qwidget.html#visible-prop for the widget, you do not want to see and vice versa. This can be used for QLabel and QPushButton and lot others.


Log in to reply