3

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;
ricky
  • 2,058
  • 4
  • 23
  • 49
  • 2
    What for? You will not be able to add other methods to `Ui_MainWindow`, as it will be overwritten next time you build the project. As a workaround, you might create a "mix-in widget", add it to the main window with zero size and get all it's methods through `ui->mixin->foo()`. – Sergey Dec 02 '16 at 01:59
  • Thanks Sergey. Yes, I want to be able to add some basic methods to `Ui_MainWindow`. And I want it can generate the expected `Ui_MainWindow` class every time when user build the project. Your workaround seems doable, but I'm trying to find a more elegant way. – ricky Dec 02 '16 at 06:08

1 Answers1

5

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();
  }
};
Kuba hasn't forgotten Monica
  • 95,931
  • 16
  • 151
  • 313