Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

qt access ui elements from another 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.



  • @amarism said in qt access ui elements from another class?:

    Now I want to use QprogressBar object directly inside my demo.cpp file.

    No, you don't. That's bad design. Your object in demo.h/cpp should send a signal to notify the progress change but it's the responsibility of the object in mainwindow.h/cpp to pick up that signal and use it to update the progressbar



  • @amarism said in qt access ui elements from another class?:

    I tried all possible combinations, connections

    Could post any of them?

    @VRonin is right, letting your Demo class know about specifics of your UI is a bad design idea. Let's say that next month you change the QProgressBar into a LCD display to show progress, you'll need to change Demo class as well.

    Ideally, your Demo class should have a signal progressUpdated(int) that you'll emit whenever you know some progress have occurred. Then you connect such signal with a slot in your MainWindow class and act accordingly. Pseudo-code:

    void Demo::superDuperAction()
    {
        // lots of things to do, that will progress over time
        progress++;
        ...
        emit progressUpdated(progress);
    }
    

    mainwindow.h

    class MainWindow :
        ...
        slots:
        updateProgress(int);
    
    private:
         Demo demo;
         ....
    

    mainwindow.cpp

    ...
    void doSomething() {
        demo.doSomeActionThatNeedsShowingProgress();
        ...
    }
    
    ...
    
    void MainWindows:updateProgress(int progress) {
        ui->progressBar->update(progress);
    }
    

Log in to reply