PDA

View Full Version : Connect one form to another



bakslash
17th November 2016, 18:11
I am trying to connect a QFontCombo box from font_select to a QTextBox in mainwindow. I am new to Qt and have no idea how to use the connect() function to do so as i want user to select font in the new form and hit an OK buton and use that font in the text box on the previous form. Can anone please help???

d_stranz
18th November 2016, 04:20
If all you want the user to do is select a new font, then using a QFontDialog would be easier. If your form is more complex than that (with more than just font properties on it), then you could do something like this:

1 - Create a signal on the form called fontChanged() (or something like that). In the form constructor, connect the QFontComboBox::currentFontChanged() signal to this signal.



// MyCostomForm.h
class MyCustomForm : public QWidget
{
Q_OBJECT

public:
MyCustomForm( QWidget * parent = 0 );
~MyCustomForm();

signals:
void fontChanged( const QFont & font );

// ...

private:
Ui::MyCustomForm * ui;
};

// MyCustomForm.cpp
MyCustomForm::MyCustomForm( QWidget * parent ) : QWidget( parent ), ui( new Ui::MyCustomForm )
{
ui->setupUi( this );

// It's OK to connect signal to signal
connect( ui->font_select, &QFontComboBox::currentFontChanged, this, &MyCustomForm::fontChanged );
}


2 - Create a slot on MainWindow called onFontChanged() (or something like that). When you create the instance of MyCustomForm, connect this slot to the form's signal:



// MainWindow.h

class MainWindow : public QMainWindow
{
// ...

private slots:
void onFontChanged( const QFont & font );

private:
MyCustomForm * myForm;

};

// MainWindow.cpp

MainWindow::MainWindow( QWidget * parent ) : QMainWindow( parent )
{
myForm = new MyCustomForm( this );

// Here we connect signal to slot
connect ( myForm, &MyCustomForm::fontChanged, this, &MainWindow::onFontChanged );

// ...
}


3 - In the slot, do what you need to change the font in the QTextEdit:



void MainWindow::onFontChanged( const QFont & newFont )
{
// Change the font in the QTextEdit
}


This is the general model used to transfer information between two GUI windows in Qt. You should never expose the actual QWidget variables in the GUI windows by making them public. Instead, handle their signals locally within each GUI window, and if the change needs to be sent to other windows, implement signals to transmit them. In the receiving window, implement a slot that connects to the signal from the other window.

With this model, you can completely replace the second window with a different implementation without any effect on the receiving window, so long as the signals and slots remain the same.

bakslash
18th November 2016, 04:48
Thank you so much!!! Everything makes so much more sense now :)