首先,当您在 MainWindow::on_StartButtonClicked 函数中创建 MyServer 对象时,需要动态创建该对象,否则它将超出范围并被删除,但也许您只是显示这一点,而不是其声明在主窗口标题中。
至于您的问题,您的 UI 连接到 MainWindow,因此使用 Qt 的信号和插槽将信号从 MyServer 对象连接到 MainWindow 并向其发送要显示的文本。然后MainWindow可以将其添加到textBrowser中。像这样的事情:-
void MainWindow::on_startButton_clicked()
{
MyServer* mServer = new MyServer;
connect(mServer SIGNAL(updateUI(const QString)), this, SLOT(AppendToBrowser(const QString)));
}
然后而不是调用 ui->qtextBrowser->append("hellohallo");在新连接中,发出信号:-
emit updateUI("hallo hallo");
在 MainWindow 中,您可以使用 AppendToBrowser 函数:-
void MainWindow::AppendToBrowser(const QString text)
{
ui->textBrowser->append(text);
}
或者,您可以将 UI 对象的指针传递给 MyServer 并从那里调用它,但信号和槽方法要干净得多。
=========== 编辑标题,回应评论======================
//骨架我的服务器标头
class MyServer : public QObject
{
QOBJECT
signals:
void updateUI(const QString text);
};
// 骨架主窗口标题
class MainWindow : public QMainWindow
{
private slots:
void AppendToBrowser(const QString text);
};