vendredi 18 septembre 2015

C++: Create an anonymous class for event handlers

Disclaimer: This description contains a lot of Qt specifics. They are not necessary to answer the question, I just wanted to give you the background.

I need to react on the focusInEvent of a QTextEdit. Unfortunately this is not available as a signal, that's why I need to subclass QTextEdit. Since this is the only change I need, I would like to use an anonymous subclass

Like this:

myTextEdit =new QTextEdit(){
            void focusInEvent(){
     //code here
     }
};

This is the code I would write in Java, it doesn't compile in c++. All following code is within the constructor of a custom QWidget. The QTextEdit is contained in this widget and should be initialized in its constructor.

Strangely this code compiles:

class MyTextEdit:protected QTextEdit{
    void focusInEvent();
};
auto myTextEdit=new MyTextEdit();

but is useless, since I can't assign an instance of myTextEdit* to a pointer to QTextEdit. Somehow polymorphism fails. This code doesn't compile:

class MyTextEdit:protected QTextEdit{
        void focusInEvent();
    };
QTextEdit* myTextEdit=new MyTextEdit();

The compiler error is:

/home/lars/ProgrammierPraktikum/moleculator/implementation/Moleculator/gui_elements/editor.cpp:40: error: 'QTextEdit' is an inaccessible base of 'Editor::Editor(std::shared_ptr)::MyTextEdit' QTextEdit* myTextEdit=new MyTextEdit();

Actual question:

How do I create an anonymous subclass that is compatible to pointers of its superclass ?



from Newest questions tagged java - Stack Overflow http://ift.tt/1F659i7
via IFTTT

Aucun commentaire:

Enregistrer un commentaire