Evgenii Legotckoi
July 9, 2018, 4:14 p.m.

Qt/C++ - Tutorial 082. Custom widgets in the Qt Designer

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

  1. #ifndef CUSTOMBUTTON_H
  2. #define CUSTOMBUTTON_H
  3.  
  4. #include <QPushButton>
  5.  
  6. class CustomButton : public QPushButton
  7. {
  8. Q_OBJECT
  9. public:
  10. explicit CustomButton(QWidget *parent = nullptr);
  11.  
  12. // QWidget interface
  13. protected:
  14. virtual void mousePressEvent(QMouseEvent* event) override;
  15. };
  16.  
  17. #endif // CUSTOMBUTTON_H

CustomButton.cpp

  1. #include "CustomButton.h"
  2.  
  3. CustomButton::CustomButton(QWidget *parent) : QPushButton(parent)
  4. {
  5.  
  6. }
  7.  
  8.  
  9. void CustomButton::mousePressEvent(QMouseEvent* event)
  10. {
  11. // ToDo something
  12.  
  13. QWidget::mousePressEvent(event);
  14. }

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

Recommended articles on this topic

By article asked0question(s)

3

Do you like it? Share on social networks!

Благодарю, а я решил весь GUI в коде писать из-за того, что года два назад не нашел ответ на этот вопрос :) Плохо искал :C

Наверное, поэтому некоторые программисты недолюбливают Qt Designer. Приходится тратить дополнительно силы на его изучение, а иногда некотроые вещи запрятаны очень глубоко в нём.

Comments

Only authorized users can post comments.
Please, Log in or Sign up
  • Last comments
  • AK
    April 1, 2025, 11:41 a.m.
    Добрый день. В данный момент работаю над проектом, где необходимо выводить звук из программы в определенное аудиоустройство (колонки, наушники, виртуальный кабель и т.д). Пишу на Qt5.12.12 поско…
  • Evgenii Legotckoi
    March 9, 2025, 9:02 p.m.
    К сожалению, я этого подсказать не могу, поскольку у меня нет необходимости в обходе блокировок и т.д. Поэтому я и не задавался решением этой проблемы. Ну выглядит так, что вам действитель…
  • VP
    March 9, 2025, 4:14 p.m.
    Здравствуйте! Я устанавливал Qt6 из исходников а также Qt Creator по отдельности. Все компоненты, связанные с разработкой для Android, установлены. Кроме одного... Когда пытаюсь скомпилиров…
  • ИМ
    Nov. 22, 2024, 9:51 p.m.
    Добрый вечер Евгений! Я сделал себе авторизацию аналогичную вашей, все работает, кроме возврата к предидущей странице. Редеректит всегда на главную, хотя в логах сервера вижу запросы на правильн…
  • Evgenii Legotckoi
    Oct. 31, 2024, 11:37 p.m.
    Добрый день. Да, можно. Либо через такие же плагины, либо с постобработкой через python библиотеку Beautiful Soup