Sunday, June 13, 2010

How to customize the Button in Qt





In this article,we will see how to customize button.

Qt has provided the option to place any number of Texts and images at desired location over a button, but now i am showing how to place 3 Text and 1 image over a button.

First we need to subclass the Qpushbutton, then override the paintEvent() method. In the paint event method perform the drawing Text, images etc..

sample code is provided here..

//Custom button class
//Qt-articles.blogspot.com

class CustomButton : public QPushButton
{
Q_OBJECT

public:
CustomButton(QWidget *parent = 0);
~CustomButton();

public:
QString FirstName,MiddleName,Lastname;
QImage SimileIcon;
bool IsBkColorEnabled;
QColor Bkclor;

protected:
void paintEvent(QPaintEvent *);

};



//Custom button implimentation file
//Qt-articles.blogspot.com
CustomButton::CustomButton(QWidget *parent)
: QPushButton(parent)
{

}

CustomButton::~CustomButton()
{

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

p.drawText(QPoint(100,100),FirstName); //Simple Text.
p.setPen(Qt::blue); //changing the color of pen.
p.setFont(QFont("Arial", 30)); //Changing the font.
p.drawText(QPoint(100,200),MiddleName);
p.drawText(QPoint(100,300),Lastname);
p.drawImage(QPoint(300,300),SimileIcon);
p.restore();
}



No comments:

Post a Comment

Post a Comment