无法从 void 函数访问 Qt UI

Can't access Qt ui from void function

本文关键字:访问 Qt UI 函数 void      更新时间:2023-10-16

My mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
   Q_OBJECT
public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();
    void test();
private:
Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H

我的mainwindow.cpp文件

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
}
void MainWindow::test()
{
    ui->textBrowser->append("Hello world");
}

QT设计器说"ui没有在这个范围内声明",但我在同一个cpp文件中使用它。

编辑*增加mainwindow.h获取更多信息

test()必须是类MainWindow的成员方法:

在<<p> strong> mainwindow.cpp
void MainWindow::test()
{
    ui->textBrowser->append("Hello world");
}

还必须添加mainwindow.h:

class MainWindow : public QMainWindow
{
    Q_OBJECT
public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();
    void test(); //<<
    // ...
};