Periodically, questions arise about the inheritance of widgets and the use of inherited widgets within the graphic designer Qt Designer.
If the application of the widget within the code as a whole is understandable, then how to fasten the custom widget to the ui form at first glance is not clear.
Let's look at an example of the inherited QPushButton button.
CustomButton
The class CustomButton is given, which is inherited from QPushButton and in it the method mousePressEvent is redefined. You will not see anything special in this code, it just shows how to write a class that is inherited from a widget in Qt.
CustomButton.h
#ifndef CUSTOMBUTTON_H #define CUSTOMBUTTON_H #include <QPushButton> class CustomButton : public QPushButton { Q_OBJECT public: explicit CustomButton(QWidget *parent = nullptr); // QWidget interface protected: virtual void mousePressEvent(QMouseEvent* event) override; }; #endif // CUSTOMBUTTON_H
CustomButton.cpp
#include "CustomButton.h" CustomButton::CustomButton(QWidget *parent) : QPushButton(parent) { } void CustomButton::mousePressEvent(QMouseEvent* event) { // ToDo something QWidget::mousePressEvent(event); }
Adding a custom widget to the ui form
1) Given the Widget class form, in which there is nothing
2) Add to it the standard QPushButton button
3) Call the context menu with the right mouse button and click "Promote to..."
4) In the opened dialog box, enter the name of the converted class and the name of the header file. In our case this will be:
- class name CustomButton
- header file CustomButton.h
And click the add button in the dialog box
5) Select the converted class and click the convert button
Благодарю, а я решил весь GUI в коде писать из-за того, что года два назад не нашел ответ на этот вопрос :) Плохо искал :C
Наверное, поэтому некоторые программисты недолюбливают Qt Designer. Приходится тратить дополнительно силы на его изучение, а иногда некотроые вещи запрятаны очень глубоко в нём.