Qt访问每个类中的查看器对象?

Qt access viewer object in every class?

本文关键字:对象 访问 Qt      更新时间:2023-10-16

我的主窗口中有一个进度条对象(ui->QprogressBar(.cpp。但是,我想在另一个类(readerfile.cpp(中使用此对象。

主窗口.h

演示.h

来源

主窗口.cpp

演示.cpp

我大部分时间都使用此方法调用对象:- 使用函数调用,例如 -mainwindow.cpp我将调用此函数

mainwindow->isFunction(ui->QprogressBar);

isFunction 在我的演示.cpp文件中可用

void demo :: isfunction (QProgressBar *progress)

但是,现在我想直接在我的演示.cpp文件中使用 QprogressBar 对象。 我尝试了所有可能的组合,连接,但无法使其工作。 所以有人可以解释一下,如何从类演示访问 UI 元素对象。

任何解决方案的想法都将是一个很大的帮助。 谢谢。

要从另一个类获取指向对象的指针,您需要实现一个返回此指针的公共函数。我举个小例子:

头文件中的类MainWindow将包含一个函数progressbar()

mainwindow.h

//...
class MainWindow : public QMainWindow
{
Q_ObBJECT
public:
QProgressBar *progressbar();   //returns a pointer to the QProgressBar
//..
private:
//..
};

此函数以如下方式实现mainwindow.cpp

QProgressBar *MainWindow::progressbar()
{
return ui->progbar;    //I just called it like this to avoid confusion, it's the just the name you defined using QtDesigner
}

然后,如果您的类中有MainWindow实例,则demo.hpp

//..
class Demo : public QObject
{
Q_OBJECT
public:
//..
private:
MainWindow *window;
//..
}

您可以通过调用demo.cpp中的函数来访问QProgressBar

QProgressBar *bar;
bar = window->progressbar(); 

我不得不说,在另一个类中有一个MainWindow实例是不寻常的。 通常,您的QMainWindowQApplication是程序的主要入口点,并且其中有其他类的实例,而不是相反。