A beginner's question
-
Hi, I am new to Qt and I have the following question: I declared an pointer to MainWindow in the main window class:
Ui::MainWindow *ui;
In another class, I first declare an object of main window class, then when I tried to use the ui pointer, the compiler said member access into incomplete type, forwarded declaration.
MainWindow mWindow; mWindow.ui->labelText->setText("Msg"); // member access into incomplete type
This maybe seems like a C++ question, but I am very new to Qt, please help me out, thank you
-
Hi
The UI of a Widget is private so you cannot access it from other class.
While you can make it public, it's not a good way as it fast leads to intermixed and tightly coupled code.What works much better is that you define a public method to call from the outside
like ( in .cpp, remember to add to .h also)
MainWindow::SetMessageText(QString msg) {
ui->labelText->setText(msg);
}and from outside
MainWindow mWindow;
mWindow.SetMessageText("Msg");Just as a note.
(since its often a beginners mistake)In this other class you create a new instance of MainWindow.
So its not the one you might also have created in main.cpp !
and if its inside say a buttons click it will very fast be deleted as its a local variable and will be deleted as
soon as the function ends. So most likely will see nothing on screen. -
-
Hi
Well the normal way is to use signal and slot
https://doc.qt.io/qt-5/signalsandslots.htmlWhere do you create the other window ?
You click a button to open or how ? -
Hi,
Since you said you are learning: stop immediately anything you want to do with threads. This is an advanced topic that you should turn to only when knowing correctly the basics. All the more since you can't manipulate GUI elements outside the GUI thread which is usually the main thread.
Also the asynchronous nature of Qt allows for a large part to avoid using threads. -
Hi
Can you show what you want to reuse from MainWindow in other class?
One option is to connect the two class in main.cpp or in MainWindow
depending on how your other class comes into play. -
@QTLeearn said in A beginner's question:
I create it because there are some methods(functions) inside the MainWindow class
Sounds like you put those methods in wrong place. Either you make these methods static (if this is possible), or (better) put these methods in another class which will cover this functionality.