Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

QT creator how to make an UI generated class inherit other class?

Tags:

c++

qt

uic

We know that, when use QT creator to build a project with a ui file (eg. mainwindow.ui), it will automatically generate a .h file with a class definition (eg. ui_mainwindow.h) for that .ui file. The generated class in the .h will be as follow:

qt .ui file generated class

My question is how to make the generated class would be as following:

QT_BEGIN_NAMESPACE

class Ui_MainWindow : MyBaseWindow
{
public:
    QMenuBar *menuBar;
    QToolBar *mainToolBar;
    QWidget *centralWidget;
    QStatusBar *statusBar;
like image 582
ricky Avatar asked Jan 25 '26 05:01

ricky


1 Answers

Yes, I want to be able to add some basic methods to Ui_MainWindow

No, you don't really.

The Ui_MainWindow class has never been meant to be modified. Perhaps you're trying to use Qt Designer as a code editor? It isn't. The .ui file is not meant to carry any code with it. Thus the output generated from it isn't meant to carry code you wrote either - only code that implements the design of the GUI.

If you want to add methods, you should add them directly to the widget that uses the Ui:: class. After all, it is a value class used to hold a bunch of pointers to stuff. You should store it by value inside of your widget, and add methods to the widget class itself. You can even make your widget class derive from the Ui:: class:

class MyWidget : public QWidget, protected Ui::MyWidget {
  ...
};

That makes any methods of MyWidget as good as the methods you'd have added to Ui::MyWidget itself.

I can recall one instance where I wanted to modify a uic-generated class, and that was to add a method to it. It was for convenience and to keep the existing code minimally changed in an attempt to fix said code. To do so, you add the methods to the derived class:

template <typename T> MyUi : public T {
  void myMethod();
};

class MyWidget : public QWidget {
  MyUi<Ui::MyWidget> ui;
  ...
  MyWidget(QWidget *parent = nullptr) : QWidget(parent) {
    ui.setupUi(this);
    ui.myMethod();
  }
};
like image 173
Kuba hasn't forgotten Monica Avatar answered Jan 26 '26 21:01

Kuba hasn't forgotten Monica