我想创建一个按钮小部件,其中包含以下元素:
由于我希望QPushButton
超过QToolButton
,因此我面临图标/文字对齐的已知问题(请参阅here和here)。
所以我的方法是专门化QPushButton
类并覆盖paintEvent
方法(参见下面的代码)。如果我只需要手动绘制文本并将其余部分(图标和背景)留给父类,那就太好了。但是现在它似乎没有绘制文本。
这是可能的吗?我的错误是在其他地方,或者我必须自己画画?
class MyPushButton : public QPushButton
{
public:
MyPushButton() : QPushButton() {}
virtual ~MyPushButton() = default;
protected:
virtual void paintEvent(QPaintEvent* e) override {
QPushButton::paintEvent(e);
QPainter p(this);
p.drawText(0,0, "label");
}
};
答案 0 :(得分:1)
当然你可以这样做:
这里MyPushButton派生自QPushButton。
void MyPushButton::paintEvent( QPaintEvent *e )
{
// This will draw everything on the push button with default palette.
QPushButton::paintEvent(e);
// Anything draw past this statement will be drawn over the real
// push button with all its properties intact,
// if you won't draw anything over, your pushbutton will look like QPushButton
// Now draw your custom content here:
}
编辑1: 试试这个,用一个矩形来判断绘制的位置: 虽然我不知道为什么它不起作用。
class MyPB : public QPushButton
{
protected:
void paintEvent( QPaintEvent *e ) override
{
// This will draw everything on the push button with default palette.
QPushButton::paintEvent(e);
p.drawText( QRect( 0,0, 50, 50 ), "HelloWorld" );
}
};
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MyPB pb;
pb.show();
return a.exec();
}
编辑2: 它也适用于点,它已经按照设计进行。 因此,它确实将文本写在0,0位置,它显示如下:
所以,如果你看到,文字被绘制但是它超出了按钮的尺寸,因此你无法看到它。