以下示例代码展示了一个常见的 QT 错误:'Ui::MainWindow* MainWindow::ui' is private within this context。该错误发生在 third.cpp 中试图访问 MainWindow 类的私有成员 ui。

// globalval.h
class MainWindow; // 前向声明

extern MainWindow *pThis; // 声明全局变量

// mainwindow.cpp
#include "mainwindow.h"
#include "globalval.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
{
    pThis = this; // 保存实体指针到全局变量
}


// 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 = nullptr);
    ~MainWindow();

private:
    Ui::MainWindow *ui;
};

#endif // MAINWINDOW_H

// mainwindow.cpp
#include "mainwindow.h"
#include "globalval.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    pThis = this; // 保存实体指针到全局变量
}

// third.cpp
#include "mainwindow.h"
#include "globalval.h"

int someFunction()
{
    int value = pThis->ui->led_time->text().toInt(); // 使用全局变量
    // ...
}

这个错误是因为在 third.cpp 中访问了 MainWindow 类的私有成员 ui。解决这个问题的方法有两种:

  1. 在 MainWindow 类中添加一个公有的 getter 函数,用于获取 ui 指针:
// mainwindow.h
public:
    Ui::MainWindow* getUi() const;

// mainwindow.cpp
Ui::MainWindow* MainWindow::getUi() const
{
    return ui;
}

然后在 third.cpp 中使用 getUi() 函数来获取 ui 指针:

int someFunction()
{
    int value = pThis->getUi()->led_time->text().toInt(); // 使用 getter 函数
    // ...
}
  1. 将 third.cpp 中的代码移到 MainWindow 类中,作为一个成员函数:
// mainwindow.h
public:
    int someFunction();

// mainwindow.cpp
int MainWindow::someFunction()
{
    int value = ui->led_time->text().toInt(); // 直接访问 ui 指针
    // ...
}

然后在其他地方调用 someFunction() 函数来获取需要的值:

int value = pThis->someFunction(); // 使用成员函数

这两种方法都可以解决 'Ui::MainWindow* MainWindow::ui' is private within this context 错误。选择哪种方法取决于具体情况和代码结构。

QT 错误:'Ui::MainWindow* MainWindow::ui' is private within this context 的解决方法

原文地址: https://www.cveoy.top/t/topic/nuLb 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录