How to pass data from one form to another in Qt?

user662285 picture user662285 · Jun 1, 2011 · Viewed 17.8k times · Source

How can I pass data from one form to another in Qt?
I have created a QWidgetProgect -> QtGuiApplication, I have two forms currently. Now I want to pass data from one form to another.

How can I achieve that ?

Thanks.

Answer

Venemo picture Venemo · Jun 1, 2011

Here are some options that you might want to try:

  • If one form owns the other, you can just make a method in the other and call it
  • You can use Qt's Signals and slots mechanism, make a signal in the form with the textbox, and connect it to a slot you make in the other form (you could also connect it with the textbox's textChanged or textEdited signal)

Example with Signals and Slots:

Let's assume that you have two windows: FirstForm and SecondForm. FirstForm has a QLineEdit on its UI, named myTextEdit and SecondForm has a QListWidget on its UI, named myListWidget.

I'm also assuming that you create both of the windows in the main() function of your application.

firstform.h:

class FistForm : public QMainWindow
{

...

private slots:
    void onTextBoxReturnPressed();

signals:
    void newTextEntered(const QString &text);

};

firstform.cpp

// Constructor:
FistForm::FirstForm()
{
    // Connecting the textbox's returnPressed() signal so that
    // we can react to it

    connect(ui->myTextEdit, SIGNAL(returnPressed),
            this, SIGNAL(onTextBoxReturnPressed()));
}

void FirstForm::onTextBoxReturnPressed()
{
    // Emitting a signal with the new text
    emit this->newTextEntered(ui->myTextEdit->text());
}

secondform.h

class SecondForm : public QMainWindow
{

...

public slots:
    void onNewTextEntered(const QString &text);
};

secondform.cpp

void SecondForm::onNewTextEntered(const QString &text)
{
    // Adding a new item to the list widget
    ui->myListWidget->addItem(text);
}

main.cpp

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

    // Instantiating the forms
    FirstForm first;
    SecondForm second;

    // Connecting the signal we created in the first form
    // with the slot created in the second form
    QObject::connect(&first, SIGNAL(newTextEntered(const QString&)),
                     &second, SLOT(onNewTextEntered(const QString&)));

    // Showing them
    first.show();
    second.show();

    return app.exec();
}