There is the complete process:
- Create a project, choose Base class: QWidget, including .h .cpp .ui
- [Add New...] -> create a [ C class] -> choose base class: [QWidget], but named myLabel.
- Open mylabel.h, change QWidget of including file and parent class to QLabel
mylabel.h
#ifndef MYLABEL_H
#define MYLABEL_H
#include <QLabel>
class myLabel : public QLabel
{
Q_OBJECT
public:
explicit myLabel(QWidget *parent = nullptr);
signals:
};
#endif // MYLABEL_H
- Open mylabel.cpp, change the parent class into QLabel too, and set text content
mylabel.cpp
#include "mylabel.h"
myLabel::myLabel(QWidget *parent)
: QLabel{parent}
{
this->setText("test");
}
widget.h
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
QT_BEGIN_NAMESPACE
namespace Ui { class Widget; }
QT_END_NAMESPACE
class Widget : public QWidget
{
Q_OBJECT
public:
Widget(QWidget *parent = nullptr);
~Widget();
private:
Ui::Widget *ui;
};
#endif // WIDGET_H
widget.cpp
#include "widget.h"
#include "ui_widget.h"
Widget::Widget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::Widget)
{
ui->setupUi(this);
}
Widget::~Widget()
{
delete ui;
}
- Now i got a custom class, and create a label in the widget.ui
add a widget, put the label in, choose widget and label, ctrl L
just like this - Promote label to myLabel.
label was promoted to myLabel - Run.
running result
This isn't what i expect.
So, why the text of label didn't change? or maybe something ignored? plz, even a keyword that can help me searching...
CodePudding user response:
Check the code of setupUi
method.
When you use QT Designer to create your widget, each widget has some properties (like geometry, object name, initial text for label etc) which have to be initialized. This is done in setupUi
. The code corresponding your case may look like:
void setupUi() {
label = new myLabel(widgetParent); // setText with test
label->setObjectName(...
label->setGeometry(...
label->setAlignment(...
label->setText(TEXT_FROM_DESIGNER); // <---
}
The text test
set by constructor of myLabel
widget is overwritten by calling setText
in setupUi
method with text choosen in Designer.
If you want to change some properties of created widgets it should be done after setupUi
:
Widget::Widget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::Widget)
{
ui->setupUi(this);
// change label's text
}