Qt World Summit: Submit your Presentation

How to paint rectangle around a button considering Padding and margins

  • QPushButton {
    color: #333;
    border: 2px solid #555;
    border-radius: 20px;
    border-style: outset;
    padding: 15px;

    Now there is a padding and margin has been set on my pushbutton. How to draw a rectangle around the pushbutton after applying the margins and padding. So i can visualize how my button is occupying space.

    The reason i am asking this question is in my application i am using different styling for different ui elements. when i am placing it in any layouts the vertical and horizontal gaps are uneven. I want to identify why the uneven spaces are coming into picture

  • Lifetime Qt Champion

    Do you mean you want to draw on top of the pushbutton to show the actual size?
    alt text

    we cannot draw outside the button.

  • @mrjj Consider my custom widget has a layout and push button is one of the item in the layout. Now in the CUstomWidget paint function, Can i draw that rectangle by measuring the button geometry and calculating its margins and padding ?

  • Lifetime Qt Champion


    Sadly we cannot really read any values set in the stylesheet so
    you cant visualize it, if that is the goal.
    We can only show the true geometry (the red frame).

  • @mrjj said in How to paint rectangle around a button considering Padding and margins:

    We can only show the true geometry (the red frame).

    How can we show the true geometry ?? does the geometry() interface provides it ?

  • Lifetime Qt Champion


    Well the function
    Tell its client area
    geometry() tells location within the Parent but for widgets (non window)
    also the size.

    What i did with the sample was to subclass QPushButton

    #include <QPushButton>
    #include <QPainter>
    class VisButton : public QPushButton
        explicit VisButton(QWidget *parent = nullptr) : QPushButton(parent) {  
        virtual void paintEvent(QPaintEvent *event) override
            QPushButton::paintEvent(event); // paint as normal
            QPainter p(this);
            p.drawRect(0,0, width()-1, height()-1); // paint frame.
    #endif // VISBUTTON_H

    and then promote it
    alt text

    Then it draws itself according to the stylesheet and we "overlay"
    a red frame.

    Not 100% sure, its what you want but it will show how the margins is in relation to the
    Widgets area

  • Thanks... I ll try this

  • Lifetime Qt Champion


    You might also want to check KDAB's GammaRay to inspect your application.

Log in to reply