qt c emit textbrowser
我有一个非常简单的服务器应用程序,可以在控制台中完美运行。
现在,我切换到gui并创建了一个新项目,几乎所有内容都与控制台项目一样。
差异之一是显示我的输出的方式。现在必须使用
只能在mainwindow.cpp中调用此ui。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | #include"mainwindow.h" #include"myserver.h" #include"ui_mainwindow.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); } MainWindow::~MainWindow() { delete ui; } void MainWindow::AppendToBrowser(const QString text) { ui->textBrowser->append(text); } void MainWindow::on_startButton_clicked() { MyServer* mServer = new MyServer; connect(mServer, SIGNAL(updateUI(const QString)), this, SLOT(AppendToBrowser(const QString))); } |
在MyServer.cpp中,我必须使用connect函数(请参见上文)并向mainwindow.cpp发出信号updateUI。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | #include"myserver.h" #include"mainwindow.h" MyServer::MyServer(QObject *parent) : QObject(parent) { server = new QTcpServer(this); connect(server,SIGNAL(newConnection()), this, SLOT(newConnection())); if(!server->listen(QHostAddress::Any,1234)) { emit updateUI("Server Error"); } else { emit updateUI("Server started"); } } void MyServer::newConnection() { QTcpSocket *socket = server->nextPendingConnection(); socket->write("Hello client!"); socket->flush(); socket->waitForBytesWritten(3000); socket->close(); emit updateUI("Socket closed"); } |
问题来了:我的文本浏览器仅显示最后一个发射命令"套接字已关闭"。我调试程序,单击启动按钮(启动服务器,并将信号(updateUI)与插槽(appendToBrowser)连接),然后通过telnet连接到程序。
该程序到目前为止运行良好,以至于我可以看到" hello client"和telnet上的退出信息,但仍然只有最后一个通过" Socked Closed"发出的输出。
在开始的第一刻,我以为我的发射可能会相互覆盖,但是那不可能,因为在我单击startButton后应该看到一个"服务器已启动"或"服务器错误"。
有什么办法解决这个问题吗?我现在和c和qt一起工作了大约3周,我必须承认我很快就很困惑,所以希望你们能理解我的问题!到目前为止非常感谢。
这很正常,如果您在MyServer的构造函数中进行连接,则尚未将其信号连接到主窗口,因此它不会显示异常。
一个基本的解决方法是将连接代码(至少是if / else部分)移到一个方法中,然后在MainWindow :: on_startButton_clicked()插槽中将它们连接在一起之后调用该方法...