Creating a custom button with two labels.
-
Hello,
I'm trying to create a custom button that has two labels. It has to look like this:I created a subclass of QPushButton to override the paintEvent() method, with no luck.
This is the code:
ResultButton.hclass ResultButton : public QPushButton { Q_OBJECT public: explicit ResultButton(QWidget* parent = nullptr, QString mainText = nullptr, QString lowText = nullptr); virtual ~ResultButton(); void setLowerText(QString s); QString getLowerText(); protected: virtual void paintEvent(QPaintEvent* e) override; private: QLabel lowLabel; };
ResultButton.cpp
ResultButton::ResultButton(QWidget *parent, QString mainText, QString lowText) : QPushButton(parent) { setText(mainText); setLowerText(lowText); setStyleSheet("background-color:#304A8D; width:250px;font-size:20px;height:50px;border-radius: 10px;color:white;margin-bottom:1px;"); } ResultButton::~ResultButton() {} void ResultButton::setLowerText(QString s) { lowLabel.setText(s);} QString ResultButton::getLowerText() { return lowLabel.text();} void ResultButton::paintEvent(QPaintEvent *e) { QPushButton::paintEvent(e); if (!lowLabel.text().isEmpty() && !text().isEmpty()) { QPainter painter(this); int x = width() / 2; // middle of the button int y = (height() - lowLabel.height()) / 2; painter.drawText(x,y,lowLabel.text()); } }
This doesn't work. When I add one of these new buttons, I only get a regular QPushButton. I only see the mainText added. The lowText does not get added to the button (I mean it's not seen).
This:
is what I see after the execution of the following code:ResultButton* rb = new ResultButton(this, "Ensayo 600", "15/5/2022");
Can anyone help me?
Thanks in advance. -
can you simply create a QVBoxLayout in class ResultButton and then add the two labels to the layout?
ResultButton::ResultButton(QWidget *parent, QString mainText, QString lowText) : QPushButton(parent) { auto vlayout = new QVBoxLayout( this ); vlayout->addWidget( new QLabel( mainText, this ) ); vlayout->addWidget( new QLabel( lowText, this ) ); }
-
@JoeCFD Thanks for the response. This works but now I have a problem with the size of the text. I see this when executing the code you provided:
As you can see, the text is displayed but it's at the left and of the same size. How can I change the sizes of the texts separately to make them look like the example I showed before?