简体   繁体   English

QT如何将变量传递给主窗口

[英]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 ...).我对 QT 和 C++ 很陌生,我需要将一些变量传递给主窗口(即: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.在 Qt 中,UI 组件之间的通信使用信号和插槽进行。 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:SomeWindow类的某些事件处理程序中,您将拥有:

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

In another window you would, for example, want to synchronize its own a_copy variable:例如,在另一个窗口中,您希望同步它自己的a_copy变量:

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将它们联系在一起:

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.有时将信号传播到AnotherWindow是有意义的,这样您就可以从类内部向它附加更多的处理程序。 In that case you would create an aChanged(int a) signal in AnotherWindow and connect the SomeWindow::aChanged signal to it.在这种情况下,您可以创建一个aChanged(int a)在信号AnotherWindow和连接SomeWindow::aChanged信号给它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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