Question

So I have a GUI I designed in QT creator.

Because I have to add a createWindowContainer widget, I have to add a widget to my code via c++. I am adding a simple label to test the best way to this. Unfortunately, though the program compiles, the widget is not shown.

My main window is in fact shown, sans the desired widget.

So I have these lines:

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{


     ui->setupUi(this);

     ui->gridLayout->addWidget(new QLabel("test"),0,0);

     // MainWindow does other stuff 

     ui->setupUi(this); 

From what I've read, this should be correct. What am I doing wrong? Is there a good way to debug this?

Edit: Found the problem. Added a second ui->setupUi to reflect the error that caused the problem. If you call this twice, it appears to erase any widgets you added after you call it the first time.

Was it helpful?

Solution

You are calling the UI setup method twice, but more importantly: the second call is made after the explicit widget addition to the "default" UI.

That is not good because then the widget is "cleared" by the second since it will set up the UI based on your UI file again which does not contain the widget as that is added explicitly, so just remove that line.

Therefore, you should be writing this instead:

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{


     ui->setupUi(this);

     ui->gridLayout->addWidget(new QLabel("test"),0,0);

     // MainWindow does other stuff
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top