0

I am trying to implement a Qt push button and some of its properties are going to change under certain circumstances, such as the size, the color and the text field. While I have implemented most of the functionality, I'm looking to add (probably) another text field at a custom place over the button which is going also to change according to different input. For example:

Desired button layout

Desired button layout

In this example, I want to be able to change dynamically both the numeric value and the currency. Is there a way to do it, or something similar?

EDIT: I tried to derive my button class from QPushButton and add some extra text in it, but with no luck. Below you'll find the relevant code:

.h file:

namespace Ui {
class myButton;
}

class myButton : public QPushButton
{
    Q_OBJECT

public:
    explicit myButton(QWidget *parent = 0);
    ~myButton();

    void setSize(int _xs, int _ys);
    void setPosition(int _xp, int _yp);

private:
    Ui::Tile *ui;
    int xSize = 95;
    int ySize = 95;

protected:
   void paintEvent(QPaintEvent *);

};

.cpp file

myButton::myButton(QWidget *parent) :
    QPushButton(parent),
    ui(new Ui::myButton)
{
    ui->setupUi(this);
}

myButton::~myButton()
{

}

//Paint event of button
void myButton::paintEvent(QPaintEvent *paint){
    QPushButton::paintEvent(paint);
    QPainter p(this);
    p.save();

    p.drawText(QPoint(80,10),"FirstName"); // Simple Text.
    p.setPen(Qt::blue);                    // Changing the color of pen.
    p.setFont(QFont("Arial", 50));         // Changing the font.
    p.drawText(QPoint(80,20),"MiddleName");
    p.drawText(QPoint(80,30),"Lastname");
    p.restore();
}

Then I'm calling my new button with something like:

myButton *newBtn2 = new myButton(this);
newBtn2->show();
Foufoutos
  • 17
  • 5
  • You can set text to the button like this: `ui->pushButton->setText("a123,45 \n dollars");` – Farhad Aug 22 '17 at 07:49
  • Yes that's true and I already did that. **EDIT** The issue is that the text in the second line should be aligned to the right and since I want also the button to be resizable, the result is not the same in a small and a larger button – Foufoutos Aug 22 '17 at 07:51
  • You should look into widget style sheets. They really knocked implementing that one out of the park. – CodeLurker Aug 22 '17 at 08:06
  • This is the best solution https://stackoverflow.com/questions/26852340/two-colours-text-in-qpushbutton – Eligijus Pupeikis Aug 22 '17 at 08:10
  • Possible duplicate of [Two colours text in QPushButton](https://stackoverflow.com/questions/26852340/two-colours-text-in-qpushbutton) – m7913d Aug 22 '17 at 20:11
  • I tried following the solution from the question you suggested by deriving my button class from the QPushButton. I had no luck with this approach since, it still doesn't show any extra text on it. I've edited my question by adding some code so you can have a look at it. – Foufoutos Aug 24 '17 at 08:35

0 Answers0