[英]Use QT MainWindow in worker thread
I have to manage a MainWindow updated by more udp channel messages. 我必须管理由更多udp频道消息更新的MainWindow。 Furthermore, reading a configuration file, i have to show or not main window and if not manage/dispatch/filter the udp messages to another application. 此外,读取配置文件,我必须显示或不显示主窗口,如果没有管理/调度/过滤udp消息到另一个应用程序。 Is it possible to define an engine class that manages communication and updates Mainwindow if it is shown? 是否可以定义管理通信的引擎类并更新Mainwindow(如果显示)? How can i manage Mainwindow? 我如何管理Mainwindow? Maybe use a singleton? 也许使用单身人士? What i would do (pseudo code): 我会做什么(伪代码):
main.cpp: main.cpp中:
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Engine app();
app.run();
return a.exec();
}
Engine.cpp Engine.cpp
Engine::Engine( QObject *parent):
QObject(parent)
{
show_mainwindow = false;
thread = new QThread();
Worker = new Worker();
// Filter/Dispatch
Worker->moveToThread(thread);
connect(Worker, SIGNAL(error(QString)), this, SLOT(errorString(QString)));
connect(thread, SIGNAL(started()), Worker, SLOT(process()));
connect(Worker, SIGNAL(finished()), thread, SLOT(quit()));
connect(Worker, SIGNAL(finished()), Worker, SLOT(deleteLater()));
connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));
thread->start();
// Message Receiver (more)
UdpRecvr = new Receiver();
connect(UdpRecvr, SIGNAL(receivedMsg(const QByteArray)), udpManager, SLOT(processMsg(const QByteArray)));
//Mainwindow Singleton used to update with SIGNAL/SLOT
WINDOWINSTANCE = MainWindow::GetInstance();
if(show_mainwindow)
{
WINDOWISTANCE->show();
}
}
Also in UdpRecvr class i would use MainWindow Singleton. 同样在UdpRecvr类中我会使用MainWindow Singleton。 I have read that using singleton with SIGNAL/SLOT is thread-safe. 我已经读过使用带有SIGNAL / SLOT的单例是线程安全的。 Is this a proper design solution? 这是一个合适的设计方案吗? Thanks in advance. 提前致谢。
I usually start a dialoguing thread in the MainWindow and connect worker's SIGNALs to window's SLOTs. 我通常在MainWindow中启动一个对话线程,并将worker的SIGNALs连接到窗口的SLOT。
void MainGUI::startServerSockets() {
serverSocket = new ServerSocket(cfg_robotPort);
//serverSocket->setDebugLevel(debugLevel);
ssocketThread = new QThread(this);
connect(ssocketThread, SIGNAL(started()), serverSocket, SLOT(run()));
connect(ssocketThread, SIGNAL(finished()), serverSocket, SLOT(deleteLater()));
connect(serverSocket, SIGNAL(socketRead(const QString &)), this, SLOT(robotSocketRead(const QString &)));
serverSocket->moveToThread(ssocketThread);
ssocketThread->start();
}
In the worker you can check if the MainWindow is visible and then rise the SIGNAL, otherwise dialogue with the other application. 在工作人员中,您可以检查MainWindow是否可见,然后启动SIGNAL,否则与其他应用程序对话。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.