简体   繁体   中英

QT how to pass variables to main window

I am very new to QT and C++, I need to pass some variables to main window ( ie: int a, double b, int c ...). Over the internet they say using global variables is not an appropriate way to achieve it. So I need to use signal-slot approach. But I have no idea how to use signal slot to pass variables to different window. In that case should I declare slot in the current window and slot to another window? Would something like this work:

//somewhere in the current window
 int a=10;
 connect (&a, &QPushButton::pressed(), mainwindow, &b);

//In main window
int b;

In Qt, communication between UI components happens using signals and slots. Thus, you should communicate that some variable changed using a signal:

class SomeWindow : public QWindow {
private:
    int a;
signals:
    void aChanged(int a);
// more, of course.
}

In some event handler of the SomeWindow class, you would have:

a = someInput.toInt();
emit aChanged(a);

In another window you would, for example, want to synchronize its own a_copy variable:

class AnotherWindow : public QWindow {
private:
    int a_copy;
public slots:
    void aChangedHandler(int a);
// more, of course.
};

void AnotherWindow::aChangedHandler(int a) {
    a_copy = a;
}

Finally, you tie these together using QObject::connect :

QObject::connect(someWindow, &SomeWindow::aChanged, anotherWindow, &AnotherWindow::aChangedHandler);

Sometimes it makes sense to propagate the signal into AnotherWindow so that you can attach more handlers to it from inside the class. In that case you would create an aChanged(int a) signal in AnotherWindow and connect the SomeWindow::aChanged signal to it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM