我是Qt的新人。
我想开发一个TCP服务器程序,在新连接到达时通知用户。
我创建了一个widget项目,并为socket编程添加了一个新类。在我的类的接口中,有一个名为my server的QTcpserver对象(QTcpserver * myServer)。
我可以将newConnection()信号连接到我的类的插槽,如下所示:
connect(myServer, SIGNAL(newConnection()), this, SLOT(aConnectionArrived()));
但是,我想将newConnection()信号连接到MainWindow类的插槽。
如果您让我知道如何通过我班级的信号和插槽访问ui,我将不胜感激?
在窗口小部件中创建一个新信号并将其连接到TCP服务器(您可以将信号连接到另一个):
class MyWidget: public QWidget
{
Q_OBJECT
...
private:
QTcpServer* myServer;
signals:
void newConnectionAccepted();
}
MyWidget::MyWidget(): QWidget()
{
connect(myServer, SIGNAL(newConnection()), this, SIGNAL(newConnectionAccepted()));
}
因此,您可以在主窗口中创建连接:
MainWindow::MainWindow()
{
connect(myWidget, SIGNAL(newConnectionAccepted()), this, SLOT(processNewConnection()));
}
通过执行此操作,您不会通过在窗口小部件外部公开TCP服务器对象来破坏SOLID原则。