我有这样的代码:
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()循环中的行似乎没有执行。
请告诉我这个问题的解决办法。
更新:如@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);
}
}但没有更好的结果:-
发布于 2012-08-01 09:20:31
不能从主线程以外的其他线程更改UI。 -- QMainWindow的所有者。我认为您的CMyServer::incomingConnection是由QTcpServer线程调用的。必须使用Qt::QueuedConnection类型执行信号插槽。
https://stackoverflow.com/questions/11755724
复制相似问题