I am facing problem while Setting text in QPushbuuton.
I set the text on a button , but it never appears.
I have written a Custom Class for mousepress,mouserelease event for QPushbutton.
I Promote my QPushbutton to this class.
My code looks like :
//Customclass.h
enum ButtonState
{
Normal,
MouseOver,
Pushed
};
class CustomButtonStates : public QPushButton
{
Q_OBJECT
public:
explicit CustomButtonStates(QWidget *parent = 0,const QString &normal = "", const QString &active = "",QString strText = "");
virtual ~CustomButtonStates();
void mousePressEvent(QMouseEvent *event);
void mouseReleaseEvent(QMouseEvent *event);
void paintEvent(QPaintEvent *e);
private:
QString m_PixmapNormal;
QString m_PixmapActive;
QString m_strText;
bool m_bPressed;
ButtonState state;
public:
QImage *NormalImage;
QImage *MouseOverImage;
QImage *PushedImage;
};
// .cpp
CustomButtonStates::CustomButtonStates(QWidget *parent,const QString &normal, const QString &active,QString strText) :
QPushButton(parent)
{
m_PixmapNormal = normal ;
m_PixmapActive = active ;
m_strText = strText ;
state = Normal;
}
void CustomButtonStates::mousePressEvent(QMouseEvent *event)
{
QPushButton::mousePressEvent(event);
state = Pushed;
this->repaint();
}
void CustomButtonStates::mouseReleaseEvent(QMouseEvent *event)
{
QPushButton::mouseReleaseEvent(event);
state = Normal;
emit clicked();
this->repaint();
}
void CustomButtonStates::paintEvent(QPaintEvent *event)
{
QPainter painter(this);
QImage *pic = NULL;
NormalImage = new QImage(m_PixmapNormal);
PushedImage = new QImage(m_PixmapActive);
switch (state)
{
case Normal:
pic = NormalImage;
break;
case MouseOver:
pic = MouseOverImage;
break;
case Pushed:
pic = PushedImage;
break;
default:
pic = NormalImage;
break;
}
painter.drawImage(0, 0, *pic);
}
CustomButtonStates::~CustomButtonStates()
{
delete NormalImage;
delete MouseOverImage;
delete PushedImage;
}
In my Page :
CustomButtonStates *btnMain ;
btnMain = new CustomButtonStates(this,":/Sampl1.png",":/Sample2.png","Users");
btnMain->setText("Users");
btnMain->setGeometry(QRect(3,6,65,33));
connect(btnMain,SIGNAL(clicked()),this,SLOT(on_btnUsers_clicked()));
If you don’t need any of the stuff painted in the
QPushButtonexcept the text and your data (images/pixmaps), I suggest you can go a little deeper an directly inherits ofQAbstractButtoninstead.In your button you will add a text member (plus accesors
setText(const QString&...)andtext()) then re-implement the paint event to draw your image and at last text above this background with one of thedrawText()method of theQPainter.paintEventwill look like this :If you need fancier stuff like word wrapping, or Qt ‘css’ style to be applied to you text I suggest to use directly a
QLabeland forward text accessor to thisQLabel. In this case do not forget to re-implementresizeEventto set correctly the overlay label on the top of your button rectangle any time it is changing.