Home > Software design >  Use this outside of constructor
Use this outside of constructor

Time:06-29

MainWindow::MainWindow(QWidget *parent, GraphicalUI *graphicalUI) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);



    QLabel *label = new QLabel("Label", this);
    label->setPixmap(graphicalUI->textures["background"]);
    label->setStyleSheet("background-color: black;");

}

void buildWindow(Level *level, GraphicalUI *graphicUI) {
    QGridLayout layout = QGridLayout(this);
    
}

The problem here is found in the buildWindow() function. Obviously I cannot just use QGridLayout(this). But I want the MainWindow to be the parent of my QGridLayout. How do I do this? Also, the buildWindow function is going to be called externally.

CodePudding user response:

In your code:

void buildWindow(Level *level, GraphicalUI *graphicUI) {
    QGridLayout layout = QGridLayout(this);  
}

variable layout is a local variable in the scope of this function. When your code reaches the end of function (closing brackets), your QGridLayout layout object is destroyed. In order to avoid this, you should use pointers and the new keyword.

QGridLayout *layout = new QGridLayout(this);

now leyout is just a pointer to a QGridLayout object. This object is destroyed if you call delete layout; manually or the parent object (in this case your mainwindow object) get's destroyed. But now the problem is you can't access this QGridLayout later on from other functions because the pointer layout will be lost at the end of this function. I recommend using a class member variable like:

private:
    QGridLayout *layout;

in your header file and initialize if inside your function like:

void buildWindow(Level *level, GraphicalUI *graphicUI) {
    layout = new QGridLayout(this);  
}

Make sure you don't use the layout pointer before calling this function.

CodePudding user response:

void MainWindow::buildWindow(Level *level, GraphicalUI *graphicUI) {
    QGridLayout* layout = new QGridLayout(this);
}

Thats the solution. The function is also required to exist in the header of the class.

  •  Tags:  
  • c qt
  • Related