我正在开发一个客户端是单线程的聊天程序,但服务器将为每个连接的客户端启动一个新线程。我相信我的客户端代码是可靠的,但服务器让我感到困惑。
现在,我有一个派生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
? - 我是否以完全错误的方式解决这个问题?
- 关于为什么这不能像我期望的那样工作或如何解决它的任何其他一般性想法也将不胜感激。