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

Access to a QT instance which is declared and defined in another method



  • Hello,
    I have an QT5 Window application(QMainWindow) and an hexeditor called qhexedit (https://github.com/Simsys/qhexedit2/blob/master/src/qhexedit.cpp). The hexeditor inherits from QAbstractScrollArea.
    I have seen a code where the hexeditor was created locally in method foo and another method foo2 in the same class was able to get the instance of this hexeditor although the variable is locally to foo?

    void MainWindow::foo()
    {
       QHexEdit * hexEdit = new QHexEdit;
       setCentralWidget(hexEdit);
    }
    void MainWindow::foo2()
    {
     ???
    }
    

    Is that possible? I am not really sure. I think within the QT5 framework it is possible to get the hexeditor instance, but I don't know how. Can you give me some hints?


  • Lifetime Qt Champion

    Hi,

    It's nothing Qt specific. You can get your central widget back using centralWidget and then use qobject_cast to cast the pointer to your QHexEdit class.


  • Lifetime Qt Champion

    Hi
    Why not simply

    class QHexEdit: // forward ( the include goes to .cpp)
    class MainWindow : public QMainWindow
    {
    ....
    private:
        Ui::MainWindow *ui;
    QHexEdit * hexEdit; /// make it a memeber
    };
    
    void MainWindow::foo()
    {
    hexEdit = new QHexEdit; // new the member 
     setCentralWidget(hexEdit);
    }
    
    void MainWindow::foo2()
    {
    hexEdit->xxxx // simply acces it or any methid of MainWindow
    }
    
    

    That way any member of MainWindow can access it.



  • @mrjj Hi, I know that I can make hexedit to a member of the class. But I was very suprised that it is possible to get access to an object which was defined and declared locally in a function. Unfortunatly I can't remember the code of foo2 and I don't know the principle how to get rid of this problem.



  • @SGaist
    Thank you. I try to write a proof of concept.


  • Lifetime Qt Champion

    @ppp1
    Well, they don't get access to the actual variable from the other function.
    That would be impossible.
    However, since the Widget is inserted into the MainWindows treelike parent/child structure , you
    can get a base pointer to any Widget and use qobject_cast to convert to your
    the actual type of Widget.
    There is also other access functions to find widgets in this structure.

    // find pushbutton named button1
    QPushButton *button = parentWidget->findChild<QPushButton *>("button1");



  • @mrjj
    Thanks! I know how to get access to this object.


Log in to reply