View Full Version : How to set common variable for multiple Dailogs in Qt

21st March 2013, 12:27
I am having two dialogs,dialog1 contains (dial1.h,dial1.cpp) and dialog2 contain(dial2.h,dial2.cpp) and one common main.cpp file ,how will i set common variable for this dialogs some one help me pls...


21st March 2013, 16:08
The Qt way to share information between different parts of the GUI is to use signals and slots.

If you have a value that is in one place (for example dialog1), and you need to notify another place (dialog2) that the value has changed, then you create a signal for dialog1 (variableChanged( const MyVariable & )) and write a slot for dialog2 (onVariableChanged( const MyVariable & )). Connect the signal to the slot. In dialog1, when the user does something to change the value of your variable, dialog1 emits variableChanged( newValue ). Dialog2 receives this signal through the slot, and can update its copy of the variable. If the value can be changed in either place, then you make the same signal for dialog2, and slot for dialog1 and connect them the other way also.

The code looks something like this:

// Dialog1.h
class Dialog1 : public QDialog

Dialog1( QWidget * parent = 0 )
: QDialog( parent )
pEdit = new QLineEdit( this );
connect( pEdit, SIGNAL( textEdited( const QString & ) ), this, SLOT( onTextEdited( const QString & ) ) );

void myVariableChanged( const QString & );

public slots:
void onMyVariableChanged( const QString & )
pEdit->setText( s );

private slots:
void onTextEdited( const QString & s )
emit myVariableChanged( s );

QLineEdit * pEdit;

// Exactly the same code for Dialog2.

// main.cpp:

int main( int argc, char * * argv )
QApplication app( argc, argv );

Dialog1 dlg1;
Dialog2 dlg2;

connect( &dlg1, SIGNAL( myVariableChanged( const QString & ) ), &dlg2, SLOT( onMyVariableChanged( const QString & ) ) );
connect( &dlg2, SIGNAL( myVariableChanged( const QString & ) ), &dlg1, SLOT( onMyVariableChanged( const QString & ) ) );



Of course your code will not be the same as this. This is just a toy example to show how to communicate a value between two dialogs. What is important to see is that Dialog1 and Dialog2 do not know anything about each other. main() knows that both dialogs have a myVariableChanged() signal and an onMyVariableChanged() slot. That's it. main() doesn't know what theses slots do, and it doesn't matter. Dialog1 simply knows that when the user edits the text in the line edit, it should tell the rest of the world using its signal. Likewise, when someone out in the world changes the value, Dialog1 knows because it is listening for it through its slot. When someone tells it, it updates the user interface.