我在QPushbuuton中設置文本時遇到問題。 我在一個按鈕上設置文本,但它永遠不會出現。QPushbutton settext在QT中的問題?
我已經爲QPushbutton的mousepress,mouserelease事件編寫了一個自定義類。
我推廣我的QPushbutton這個類。
我的代碼如下所示:
//Customclass.h
枚舉ButtonState { 正常, 鼠標懸停, 推 };
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;
}
在我的網頁:
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()));
我已經添加QPushButton :: paintevent(event)作爲我的自定義繪畫事件的最後一行現在我將圖像分配給未來的按鈕? – user662285
嘗試先調用繪畫事件,然後應用您的圖像。我的錯。如果這不起作用,那麼在繪製QImage(應該是QPixmap btw)後,您將不得不自己繪製文本。 –
如何繪製文本? – user662285