Search code examples
qtqwidget

Passing variable to promoted QWidget


I have two classes:

-MainWindow

-MyWidget which is promoted in MainWindow.ui using QT Creator's design tab. Both of the class .ui's are designed in design tab.

I try to pass variables to MyWidget from MainWindow without any success. Compiler doesn't give any errors, but variables are not passing. Is there any way to do this? MyWidget works well as long as I don't import MainWindow to it or import MyWidget to MainWindow. After import I can't control MyWidget's content by code. Any suggestions?

EDIT: Made a small example and added code to pastebin, so this post won't get bloated.

MainWindow.h

MainWindow.cpp

another links are in comments


Solution

  • Your class MainWindow does not need to a MyWidget attribute. MyWidget object is actually created by Ui::MainWindow object.

    So, to access your MyWidget object (the one displayed on screen as part of MainWindow widget), use ui->widget (as widget is the name you gave the object in Qt Designer <widget class="MyWidget" name="widget" native="true"/>), instead of mw.

    Modifying mw makes no sense because this instance of MyWidget is not used for GUI display.

    You then have to change:

    connect(this, SIGNAL(text(QString, QString)),&mw, SLOT(addText(QString,QString)));
    

    into:

    connect(this, SIGNAL(text(QString, QString)),ui->widget, SLOT(addText(QString,QString)));
    

    Note: If MyWidget class needs parameters to be passed upon construction, you can remove the widgetinstanciation from your .ui file and create it locally using mw attribute of the MainWindow class as you did. But, then, to have this instance be shown on screen, you must add it to the layout of your MainWindow, like this (for example): ui->horizontalLayout->addWidget( &mw );