我有这段代码:
类CMyWindow:
class CMyWindow: public QMainWindow
{ // Q_OBJECT .... here
private:
CMyServer *server;
public:
CMyWindow(QWidget *parent): QMainWindow(parent)
{
// Setup GUI here
server = new CMyServer(this);
server->startServer();
}
void thisChangeLabelCaption(QString str) {
ui.lblStatus.setText(str);
}
}
和类CMyServer:
class CMyServer: public QTcpServer
{
protected:
void incomingConnection(int sockDesc) {
/* Why below line can't be done :-| */
((CMyWindow *) parent())->thisChangeLabelCaption("New connection");
}
}
但是incomingConnection()rountine中的行似乎没有执行。
请告诉我这个问题的解决方法。
更新 正如@vtmarvin所说,我试过这种方式:
class CMyWindow: public QMainWindow
{
private:
CMyServer *server;
protected slots:
void editLabel(QString str) {
thisChangeLabelCaption(str);
}
public:
CMyWindow(QWidget *parent): QMainWindow(parent) {
server = new CMyServer(this);
server->startServer();
}
void thisChangeLabelCaption(QString str) {
ui.lblStatus.setText(str);
}
}
class CMyServer: public QTcpServer
{
Q_SIGNAL:
void setText(QString str);
protected:
void incomingConnection(int sockDesc) {
/* Why below line can't be done :-| */
emit setText("New connection");
}
public:
CMyServer(QObject *parent): QTcpServer(parent)
{
connect(this, SIGNAL(setText(QString)), parent, SLOT(editLabel(QString)), Qt::QueuedConnection);
}
}
但没有更好的结果: - (
答案 0 :(得分:1)
You cannot change UI from other threads than the main one - 拥有QMainWindow的人。我想你的CMyServer :: incomingConnection是由QTcpServer线程调用的。您必须使用Qt :: QueuedConnection类型执行信号槽。