Frage

I have a class/ QDialog (let's call it "Frame") that contains other classes. This is what it looks like:

Frame Class

In the above screenshot, everything inside the green rectangle is actually a separate class/custom QWidget (let's call it "Page3" since it is the third item in the list) placed inside a QStackedWidget while everything outside the rectangle is part of Frame. Everything inside the rectangle is therefore separate from Frame even though it appears to be part of the same form. Clicking the Overview and SQLite Journal objects causes a separate page to load inside the QStackedWidget. All of these classes must be able to communicate with each other.

The problem is, I’m not sure how to access Frame's public methods or variables from inside Page3. See, one of the functions of Page3 is to unlock the OK button in Frame when the contents of the two password fields (Password & Repeat) match. To do this, Page3 needs to call the method that unlocks the buttons in Frame. I need to communicate with the currently-running instance of Frame instead of creating a new copy so instantiating Frame from inside Page3 doesn't work. I can't use parent() either because that simply refers to the QStackedWidget inside Frame instead of Frame itself.

I'd appreciate it if someone could tell me how to do this.

War es hilfreich?

Lösung

I prefer to do this kind of thing (communication between a child widget and its parent) using signals and slots. Why? Because if the child depends explicitly on the parent, you end up with a circular dependency, and it's harder to change your design in the future.

The simplest solution is to have Page3 emit an "unlockOk" signal which is connected to a slot in Frame which does the actual "unlocking" of the button. Frame could connect the signal and slot in its constructor, or wherever else it's actually instantiating the Page3 object.

If you want to take it a step further, you could make the signals more generic; for example, signals called "inputValid" (which would be emitted when the password fields match) and "inputInvalid", which would be connected to "unlockOk" and "lockOk" slots. The reason for doing this is that you could re-use the signals in other parts of your application if you need to, and their names clearly indicate what they're communicating.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top