Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

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;
    margin-left:10px
    margin-right:10px
    }

    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

    Hi
    Do you mean you want to draw on top of the pushbutton to show the actual size?
    like
    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

    @DonCoder

    Hi
    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

    @DonCoder

    Well the function
    https://doc.qt.io/qt-5/qwidget.html#rect-prop
    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
    {
        Q_OBJECT
    public:
        explicit VisButton(QWidget *parent = nullptr) : QPushButton(parent) {  
        }
    
    protected:
        virtual void paintEvent(QPaintEvent *event) override
        {
            QPushButton::paintEvent(event); // paint as normal
            
            QPainter p(this);
            p.setPen(Qt::red);
            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

    Hi,

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


Log in to reply