简体   繁体   English

Qt,类间通信

[英]Qt, communication between classes

I have two classes MainWindow and Worker .我有两个类MainWindowWorker MainWindow is basically responsible for GUI and the worker is for connecting with the server. MainWindow主要负责 GUI,worker 负责连接服务器。 MainWindow has an instance of Worker . MainWindow有一个Worker的实例。 If Worker receives a message from the server it is supposed to change the GUI, but I can not find a way to communicate them.如果Worker从服务器收到一条消息,它应该更改 GUI,但我找不到与它们通信的方法。 I thought about making MainWindow a singleton, and then use slots and signals.我想过把MainWindow做成singleton,然后用槽和信号。 But maybe is there an easier way, like some function to get the object of the current View?但也许有更简单的方法,比如一些 function 来获取当前视图的 object?

You mentioned signals/slots in your question, but you combined them with a singleton, which is not needed at all.您在问题中提到了信号/插槽,但您将它们与 singleton 结合在一起,这根本不需要。 You said MainWindow has an instance of Worker, so just connect to a signal from the Worker.你说 MainWindow 有一个 Worker 的实例,所以只需连接到来自 Worker 的信号。 Since you didn't provide any code, I'll make something up.既然你没有提供任何代码,我会弥补一些东西。

void Worker::doSomething()
{
    ...

    // When we get a message from the server emit a signal
    emit messageReceived();
}

...

MyWindow::MyWindow()
{
    auto worker = new Worker();

    // Connect to the Worker's signal
    connect(worker, &Worker::messageReceived, this, &MyWindow::handleMessage);

    worker->start();
}

void MyWindow::handleMessage()
{
    // The MainWindow can now do something in response to the server message
}

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

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