来自另一个类的 Qt C++ GUI 调用

bea*_*ary 3 c++ user-interface qt class undeclared-identifier

我通过 gui 拖放创建了一个按钮和一个文本浏览器。ui 是在 mainwindow.cpp 以及单击按钮功能中创建的。有一个 main.cpp 但这无关紧要,因为在单击开始按钮之前程序不会启动。

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "myserver.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_startButton_clicked()
{
    MyServer mServer;
}
Run Code Online (Sandbox Code Playgroud)

到目前为止一切都很好,问题出在 myServer.cpp 中,我想通过ui->textBrowser->append("hello hello");. 但 myServer.cpp 类不“知道”用户界面。 "ui" not declared identifier

#include "myserver.h"
#include "mainwindow.h"


MyServer::MyServer(QObject *parent) :
    QObject(parent)
{
}

void MyServer::newConnection()
{
    server = new QTcpServer(this);

    connect(server,SIGNAL(newConnection()),this,SLOT(newConnection()));

    int ports = MainWindow::port();
    if(!server->listen(QHostAddress::Any,ports))
    {

    }
    else
    {
        //here is the problem
        ui->textBrowser->append("hallo hallo");
    }
}
Run Code Online (Sandbox Code Playgroud)

通常我会创建一个新的(例如) MainWindow test;并通过它调用函数,test.function(); 但这在这里不起作用?

The*_*ght 5

首先,当您在 MainWindow::on_StartButtonClicked 函数中创建 MyServer 对象时,该对象需要动态创建,否则它将超出范围并被删除,但也许您只是在展示这一点,而不是它的声明在 MainWindow 标题中。

至于你的问题,你的 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)));
}
Run Code Online (Sandbox Code Playgroud)

然后而不是调用 ui->textBrowser->append("hallo halo"); 在 newConnection 中,发出信号:-

emit updateUI("hallo hallo");
Run Code Online (Sandbox Code Playgroud)

在 MainWindow 中,您将拥有 AppendToBrowser 函数:-

void MainWindow::AppendToBrowser(const QString text)
{
    ui->textBrowser->append(text);
}
Run Code Online (Sandbox Code Playgroud)

或者,您可以将 UI 对象的指针传递给 MyServer 并从那里调用它,但信号和插槽方法要简洁得多。

============ 编辑标题,回应评论 ======================

//骨架我的服务器头

class MyServer : public QObject
{
    QOBJECT

    signals:
         void updateUI(const QString text);
};
Run Code Online (Sandbox Code Playgroud)

// 骨架主窗口标题

class MainWindow : public QMainWindow
{
    private slots:
        void AppendToBrowser(const QString text);
};
Run Code Online (Sandbox Code Playgroud)