Avi
Avi

Reputation: 31

How to Create Custom PushButton in QT5.6.1

I am very new to QT development. Can anyone share "How to create a custom QPushButton in QT" so that custom button will have same behavior as of QPushButton only differ from custom properties. So please any clue or any direction to this will be helpful. I have tried for the Analog Clock example which is given in QT custom widget example. But I didn't find related with QPushbutton. Thanks in advance.

Upvotes: 0

Views: 6895

Answers (1)

sanjay
sanjay

Reputation: 755

Its very simple. First you need to subclass QPushButton. Add your methods to enhance it. And you are done.

For example, I have written CustomButton which have an extra method to reverse the text.

CustomButton.h

#ifndef CUSTOMBUTTON_H
#define CUSTOMBUTTON_H

#include <QPushButton>

class CustomButton : public QPushButton
{
public:
    CustomButton( const QString& text, QWidget* parent = 0 );

    // Enhancement, it will reverse the button text
    void reverseText();
};

#endif // CUSTOMBUTTON_H

CustomButton.cpp

#include "CustomButton.h"
#include "algorithm"

CustomButton::CustomButton( const QString& text, QWidget* parent )
    : QPushButton( text, parent )
{

}

void CustomButton::reverseText()
{
    QString buttonText = text();
    std::reverse(buttonText.begin(), buttonText.end());
    setText( buttonText );
}

main.cpp

#include <QApplication>
#include "CustomButton.h"
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    CustomButton w( "MyButton" );
    w.show();
    w.reverseText();
    a.exec();
    return 0;
}

The button looks like this enter image description here

If you want to do something related to look and feel. Instead of creating custom button you can use QStyleSheet

Upvotes: 1

Related Questions