How to access ?



  • Can anyone help me access a pointer in a class?

    I have a bunch of classes derived from Qt widget classes, for example I have a class called clsQtRadioButton which is derived from QRadioButton:

        class clsQtRadioButton : public QRadioButton {
        Q_OBJECT
            friend class clsXMLnode;
    

    I am adding an instance of this class to a layout using another of my functions:

    void clsQtLayout::addButton(QAbstractButton* pobjButton, const QString& crstrGroup) {
    

    I can see in the debugger that pobjButton has visibility over a protected member mpobjNode this is common to all my derived classes and is defined as private in the class. I have an access method pobjGetNode, however I cannot call this from pobjButton. Is there anyway to access mpobjNode from pobjButton ?

    I thought I could add clsXMLnode as one of the parent classes however because this class is also derived from Q_OBJECT I cannot do that.



  • Use qobject_cast and check if the cast worked (the result is not null). Also, don't expect a cast to work if it's not derived from the type you are casting to (i.e., just adding a class as friend should not make it work). Adding a class as a friend should work for what you are trying do, you may have to cast the object to the type that it's a friend of first. For example, if the object is coming in as a QAbstractButton but was created as your custom button type, cast it to your type first, then try to access private methods from an object that is of the friend type.



  • @SPlatten , wow, found something and tried, it works:

    clsXMLnode* pobjNode(reinterpret_cast<clsXMLnode*>(pobjButton));
    

    [edit] However strange results although I can now access and call methods, the results are not right, in the debugger I can see the contents of the class which are correct but stepping through its not working. For example in one of the clsXMLnode methods:

    QString clsXMLnode::strGetAttribute(QString strAttr) {
    //Does the attribute contain an object Delmtr?
        clsXMLnode* pobjNode(this);
        QString strData;
        if ( mlstAttrPrs.length() > 0 ) {
    

    In the debugger I can see mlstAttrPrs contains 6 items:
    Screenshot 2021-11-30 at 17.40.45.png
    However it will not step into the if condition and skips right over it ???



  • Use qobject_cast and check if the cast worked (the result is not null). Also, don't expect a cast to work if it's not derived from the type you are casting to (i.e., just adding a class as friend should not make it work). Adding a class as a friend should work for what you are trying do, you may have to cast the object to the type that it's a friend of first. For example, if the object is coming in as a QAbstractButton but was created as your custom button type, cast it to your type first, then try to access private methods from an object that is of the friend type.



  • This post is deleted!

Log in to reply