我有这个代码:
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);
}
}
但没有更好的结果:-(