View Full Version : Best way for a parent class to know value chosen on child class

4th October 2014, 00:53

I have a MainWindow class, on an action I create a new project type selector.


void MainWindow::on_actionFileNew_triggered()
NewDocumentSelector newdocumentselector;

I want MainWindow to know the type selected
Should I
1) Emit a signal in NewDocumentSelector and connect it to MainWindow.
2) Pass MainWindow into NewDocumentSelector on initilization,

NewDocumentSelector newdocumentselector(MainWindow);

which will then be used in NewDocumentSelector as


Is there another way? I want to follow Qt's MV pattern.
In other words I want to access parent class instance.
I have attached my project if you require more detail.


4th October 2014, 11:35
I would just call a getter on the dialog after exec()

if (newdocumentselector.exec() == QDialog::Accepted) {
m_type = newdocumentselector.type();


16th October 2014, 03:40
Or you could follow the model used by QFileDialog: emit signals whenever the user changes something the application might be interested in (like the current directory or the file extension). In your case, implement signals in the NewDocumentSelector class that are emitted when something interesting happens, and implement slots in MainWindow to listen for them. So when the user selects a new type, NewDocumentSelector emits some signal like "documentTypeChanged( DocType newType )". In your MainWindow class, you create a slot called "onDocumentTypeChanged( DocType newType )" and make a connection between the signal and slot.

I use anda_skoa's method whenever I need to retrieve a lot of information from a dialog (like a whole page of parameters). I package the parameters into a data structure and use a setter / getter combination to set the initial values and to retrieve the changes.

I use the QFileDialog method for simple parameters or when I want to dynamically keep track of what the user is doing in the dialog. (For example, I can dynamically change the color of something by listening for QColorDialog::currentColorChanged() to show the user what effect it will have while they are browsing the color selections).