我正在开发一个聊天程序,其中客户端是单线程的,但服务器将为每个连接的客户端启动一个新线程。我相信我的客户端代码是稳定的,但服务器让我感到困惑。如何从QThread启动GUI窗口?
现在,我有一个派生的QTcpSocket
类查找传入连接,当它看到一个,开始一个新的QThread
。当QThread
运行时,它会创建一个QMainWindow
(它是聊天窗口)的实例并显示它。
void secureserver::incomingConnection(int socketDescriptor)
{
securethread *thread = new securethread(socketDescriptor, this);
connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));
thread->start();
}
void securethread::run()
{
serverwindow myServerWindow;
myServerWindow.setSocketDescriptor(mySocket);
myServerWindow.show();
}
我已经得到错误stderror像下面,和QMainWindow
永远不会出现这样聊着在这一点上是不可能的。
QObject: Cannot create children for a parent that is in a different thread.
(Parent is QApplication(0xbf9e5358), parent's thread is QThread(0x98a54f0), current thread is securethread(0x99e9250)
QPixmap: It is not safe to use pixmaps outside the GUI thread
我的问题是:
- 我需要做的
QThread
的QMainWindow
父母? - 我是以完全错误的方式去谈论这个吗?
- 任何其他一般的想法,为什么这不工作,因为我期望它 或如何解决它将不胜感激。
我很困惑,为什么你的服务器有任何GUI代码在所有。在我看来,你的客户端应该是显示聊天窗口的客户端,而服务器应该是纯粹的将消息从一个客户端传递到另一个客户端的机制。 – Chris
这个想法是,你有许多客户端,一台服务器(一个本地IP地址和端口),但服务器为每个传入连接创建一个新线程。然后,服务器可以在每个窗口中仅有一个客户端进行通信,但它可以同时在这些新线程/窗口中发送/接收,因为它们将处于其自己的线程中。我没有设计这个程序的规格,所以我和你一起问为什么。 – J2N