bunto1
bunto1

Reputation: 331

Is it possible to paint QWidget both from child & parent class?

Question

I'd like to create a button widget that features the following elements:

As I'd prefer a QPushButton over a QToolButton, I'm facing the known problem (see here and here) of the icon/text alignment.

So my approach would be to specialize the QPushButton class and overwrite the paintEvent method (see the code below). It would be nice, if I only had to draw the text manually and leave the rest (icon and background) to the parent class. However it doesn't seem to paint the text for now.

Is this possible and my error is somewhere else, or do I have to paint all by myself?

Code

class MyPushButton : public QPushButton
{
public:
    MyPushButton() : QPushButton() {}
    virtual ~MyPushButton() = default;

protected:
    virtual void paintEvent(QPaintEvent* e) override {
        QPushButton::paintEvent(e);
        QPainter p(this);
        p.drawText(0,0, "label");
    }
};

Upvotes: 0

Views: 429

Answers (1)

PRIME
PRIME

Reputation: 1078

Ofcourse you can do so:

Here MyPushButton is derived from QPushButton.

void MyPushButton::paintEvent( QPaintEvent *e )
{
    // This will draw everything on the push button with default palette.
    QPushButton::paintEvent(e);

    // Anything draw past this statement will be drawn over the real 
    // push button with all its properties intact, 
    // if you won't draw anything over, your pushbutton will look like QPushButton
    // Now draw your custom content here:
}

Edit 1: Try this out, use a rectangle to tell where to draw: Though I don't know why it did not work with point.

class MyPB : public QPushButton
{
protected:
    void paintEvent( QPaintEvent *e ) override
    {
        // This will draw everything on the push button with default palette.
        QPushButton::paintEvent(e);
        p.drawText( QRect( 0,0, 50, 50 ), "HelloWorld" );

    }
};

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    MyPB pb;
    pb.show();

    return a.exec();
}

Edit 2: It works with point as well, it was already working out as per design. So, it does write the text at 0,0 location and it appears as follows:

The button when text "HelloWorld" painted at 0,0 location

So, if you see, text is drawn but it is outside the dimensions of the button, hence you can't see it.

Upvotes: 1

Related Questions