Thursday, March 29, 2012

Shape QPushButton in your own style Qt

                           Have you ever tried to create your own QPushButton shaped as you like? For example, Have you tried to create a 'L' shaped button or like a 'Enter' shaped button in your keyboad so visualize your software with a unique style? WPF in windows provides a lot of flexibility but it is having its own draw backs. Here Qt is providing flexibility of shaping button as you wish. Masking the shape of a image file, will help you to attain the button as you wish. Lets see the basics how we can do it.


class QMPButton : public QPushButton
{
  Q_OBJECT
  QSize imagesize;
public:
  explicit QMPButton(const QString &_shape,QObject *parent = 0);
signals:
public slots:
};

Here QMPButton is inherited from QPushButton, So We can get properties of QPushButton where ever you are using Object of QMPButton. QMPButton::_shape is the file name of image which we need the shape to be masked with.
 
QMPButton::QMPButton(const QString &_shape,QObject *parent) :  

QPushButton((QPushButton*)parent)

{

  QPixmap pixmap(_shape);

  imagesize = pixmap.size();

  this->setFixedSize(imagesize);

  this->setMask(pixmap.mask());

}

This Initialize and shape the button and fix it where ever you want.
Usage:


QMPButton *mbtton = new QMPButton(ui->lineEdit->text(), NULL);
  mbtton->setText("Ok");

  ui->gridLayout->addWidget(mbtton);


You can customize more by introducing style sheets and images for mouse hover, clicks etc. If you have images according to that shape will suite it more and you can now make unique style for your applications.
As like :

mbtton->setStyleSheet(QString:: 
fromUtf8("QPushButton{border-image: url(:res/pc-enter.png);}\n"
"QPushButton:hover{border-image: url(:res/pc-enter1.png);}\n"
"QPushButton:pressed{border-image: url(:res/pc-enter2.png);}"));

The Point am projecting you is that, button will be active only on the regions of the image not as a whole rectangle!

Output tested in X11 and also in Wayland:



Queries are welcome !

2 comments: