Search code examples
c++qtqprogressbar

Qt access viewer object in every class?


I have a progress bar object (ui->QprogressBar) available in my mainwindow.cpp. But, I want to use this object in another class (readerfile.cpp).

Headers

mainwindow.h

demo.h

Sources

mainwindow.cpp

demo.cpp

I use this method to call object most of the time:- Using a function call, for example -mainwindow.cpp I will call this function

mainwindow->isFunction(ui->QprogressBar);

isFunction is available inside my demo.cpp file

void demo :: isfunction (QProgressBar *progress)

But, Now I want to use QprogressBar object directly inside my demo.cpp file. I tried all possible combinations, connections and just can't get it work. So could someone please explain me, how to access UI elements object from class demo.

Any idea for the solution will be a great help. Thanks.


Solution

  • To get a pointer to an object from another class you need to implement a public function that returns this pointer. I will give you a little example:

    Your class MainWindow in the header file will include a function progressbar().

    mainwindow.h:

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

    This function is implemented in mainwindow.cpp like this:

    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
    }
    

    Then, in demo.hpp if you have an instance of MainWindow in your class:

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

    you can just access QProgressBar using by calling the function in demo.cpp:

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

    I have to say though that it's unusual to have an instance of MainWindow in another class. Usually your QMainWindow or QApplication is the main entry point to the program and you have instances of the other classes in them, not the other way around.