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

Customizing QPush Button



  • Hi All,

    I am trying customizing QPushButton's paint event. As I want to draw some text over required corners(top,left,right,bottom),and place icon at the center of push button. Please find below the code snippet.It would be so thankful if someone let's me what's wrong with this.
    #ifndef INVISIONCUSTOMBUTTON_H
    #define INVISIONCUSTOMBUTTON_H

    #include <QObject>
    #include <QPushButton>
    #include<QPainter>
    #include<QPushButton>
    class InvisionCustomButton : public QPushButton
    {
    Q_OBJECT
    public:
    InvisionCustomButton(QWidget *parent = 0);
    ~InvisionCustomButton();
    signals:

    public slots:

    protected:
    void paintEvent(QPaintEvent *paint);

    private:
    QString name_1,name_2,name_3,name_4;
    QImage audioPauseIcon;
    bool IsBkColorEnabled;
    QColor Bkclor;
    };

    #endif // INVISIONCUSTOMBUTTON_H

    #include "invisioncustombutton.h"

    InvisionCustomButton::InvisionCustomButton(QWidget *parent)
    : QPushButton(parent)
    {
    setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);

      name_1 = "topName" ;
      name_2 = "bottomName" ;
      name_3 = "leftName" ;
      name_4 = "rightName" ;
    

    }

    InvisionCustomButton::~InvisionCustomButton()
    {

    }

    void InvisionCustomButton::paintEvent(QPaintEvent *paint)
    {
    QPushButton::paintEvent(paint);//Overriding push button's paint event
    QPainter painter(this);
    painter.save();

    QRect *rect = new QRect();
    painter.drawRoundedRect(rect,5,5);//5 radius apiece
    
    painter.setPen(Qt::black);
    painter.setFont(QFont("Arial", 20));
    
    painter.drawText(QPoint(100,200),name_1,&rect);
    painter.drawText(QPoint(200,200),name_2,&rect);
    painter.drawText(QPoint(50,100),name_3,&rect);
    painter.drawText(QPoint(100,300),name_4,&rect);
    painter.drawImage(QPoint(100,400),Qt::AlignVCenter | Qt::AlignHCenter,audioPauseIcon);
    painter.restore();
    

    }

    Thank you


  • Lifetime Qt Champion

    Hi,

    You are trying to pass a pointer to a QRect rather than a const reference and said rect is empty.



  • @SGaist

    Thank you. Actually , didn't compile the code in hurry.I suppose not to pass rect ,as it can't take that parameter. And instead of passing points , i must prefer passing drawing corners like topLeft,topright so forth


  • Lifetime Qt Champion

    You misunderstood me. You should pass a QRect object not a pointer to a QRect object.



  • @Madesh-R also be aware that QRect is x (x point), y (y point), w (width in pixels), h (heigh in pixels) so you do not have x1,y1,x2,y2


Log in to reply