1

I have a MyComboBox class, inherited from QComboBox, in order to override the method focusOutEvent:

  1. mycombobox.h
class MyComboBox : public QComboBox
{
public:
    MyComboBox();
protected:
    void focusOutEvent(QFocusEvent * e) override;
};
  1. mycombobox.cpp
#include "mycombobox.h"

MyComboBox::MyComboBox()
{
    
}

void MyComboBox::focusOutEvent(QFocusEvent * e)
{
    // I will code here
    qDebug()<<"Object has lost focus";
    
    MyComboBox::focusOutEvent(e);
}

But I don't know how to declare a comboBox as object of MyComboBox class, and having a incompatible type between MyComboBox and QComboBox with this on MainWindow constructor:

MyComboBox* oMyComboBox;
oMyComboBox = ui->comboBox;
1
  • What does QtCreator have to do with anything? That's just a IDE. The problem is the same if you write your code with notepad, vim, Emacs or anything else. Commented Jul 6, 2020 at 10:19

2 Answers 2

2

Your instance on UI must have type MyComboBox. It depends on type in object creation procedure. For example if you did something like that:

QComboBox* comboBox; // This was declared on UI

ui->comboBox = new MyComboBox();

so you can use this instance as MyComboBox with qobject_cast:

QComboBox *oMyComboBox = qobject_cast<MyComboBox *>(ui->comboBox);
Sign up to request clarification or add additional context in comments.

Comments

2

You can not assign instance of Base class to a variable with type of it's inheritor. What will happen with all overridden virtual members ? So, the way you are doing is not fitting in the OOP principals. Perhaps, you can always cast the pointer to its inheritor class, but you will get runtime error when accessing class members, unless the pointer you are casting is created as instance of the inheritor.

You have to create instance of you class manually, as alexb recommended: ui->comboBox = new MyComboBox;. You dont need to use any casting. focusOutEvent() is a virtual method, and will be called in any instance of MyComboBox, even the variable is from QComboBox. Polymorphism!

Here is the bad news:

  1. First you need to delete ui->comboBox, before instantiating your MyComboBox, or the combobox you placed in the designer will stay as child in the form.
  2. Instantiating your MyComboBox and assigning it to ui->comboBox will not place your combobox at the position you placed the "original" combobox. And will not have signals->slots connections you made. You need to do it by yourself.

1 Comment

I understand @smacker. Very useful.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.