我在QPushbuuton中设置文本时遇到问题。 我在一个按钮上设置了文本,但它从未出现过。
我为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()));
答案 0 :(得分:1)
您应该在覆盖的paintEvent方法中手动绘制文本。 但更容易 - 正如OrcunC建议的那样,使用样式表。
QPushButton pb;
pb.setStyleSheet("background-image: url(:/Users/nav_on.png);");
答案 1 :(得分:1)
如果您不需要QPushButton
中除了文字和您的数据(图片/ pixmaps)之外的任何内容,我建议您可以直接更深入一点而是继承QAbstractButton
。
在你的按钮中,您将添加一个文本成员(加上加法器setText(const QString&...)
和text()
),然后重新实现绘制事件以绘制您的图像,并在上面的文本中此背景使用drawText()
的{{1}}方法之一。
QPainter
将如下所示:
paintEvent
如果你需要更好的东西,如自动换行或Qt'css'样式应用于你的文字,我建议直接使用void YourButton::paintEvent(QPaintEvent* event)
{
QPainter painter(this);
//hereadd some logic to determine witch pixmap goes background
QPixmap* selectedPixmap ...
painter.drawPixmap( rect(), *selectedPixmap);
//here add some logic to set painter pen and brush
//according to button status (enabled/checked/...)
painter.drawText( rect(), Qt::AlignCenter, text());
}
并转发文本访问者QLabel
。在这种情况下,请不要忘记重新实施QLabel
,以便在按钮矩形更改时正确设置叠加标签。
答案 2 :(得分:0)
首先尝试在自定义paintevent中调用QPushButton :: paintevent(event),然后应用自定义QImage。