PDA

View Full Version : How to access UI elements from subclass.



NuMs
1st December 2017, 10:53
Hello!

Trying to learn QT.

My current project has one GUI and I need to be able to access elements of the UI from subclasses. None of the subclasses have a UI.

How do I pass Ui::MainWindow to subclasses? Basically they need to be able to update labels or text fields.

I've tried to pass it through the constructor like below:



SubClass::SubClass(Ui::MainWindow mw) {
this->mw = mw;
}
With it defined in the header file:


class SubClass {
public:
SubClass(Ui::MainWindow mw);
Ui::MainWindow mw;
}

Which of course doesn't work. I'm guessing there's a proper way to do this but I haven't been able to find it in any of the tutorials or documentation.

Any help would be appreciated.
Thanks

ado130
1st December 2017, 18:05
Do not do it this way. Try to check the signal-slot mechanism.

d_stranz
1st December 2017, 18:06
I'm guessing there's a proper way to do this but I haven't been able to find it in any of the tutorials or documentation.

That's because none of the tutorials or documentation teach such bad programming practice.

You never want to expose the details of the UI to any class other than the one that implements it. If your UI needs to communicate changes to other parts of your program, the way to do it in Qt is to implement signals and slots.

A QLineEdit tells the world that the user has changed its contents by sending signals, like QLineEdit::editingFinished(). If the widget that contains the line edit needs to know this, you implement a slot and connect it to that signal.

If some class outside of the one that owns the line edit needs to know, you don't expose the line edit instance (or its signal) to that class. Instead, you can implement a signal for the class that owns the line edit, and in your slot that handles the line edit's signal, you can emit your own signal. The classes that want to know can then make a connection to your signal instead.

By doing it this way, you can hide the implementation of your UI from the outside world; all the world needs to know about is that your class has a signal that will be emitted every time that important piece of information changes. You are then free to change your UI in any way you want, as long as you keep your signal the same.

Read the Qt documentation on signals and slots (https://doc.qt.io/qt-5/signalsandslots.html).