是否有可能从儿童和儿童绘制QWidget?父类?

时间:2017-08-24 08:17:28

标签: c++ qt5 qwidget qpainter

问题

我想创建一个按钮小部件,其中包含以下元素:

  • 可配置的背景颜色
  • 按钮大小,透明图标
  • 可配置的定位文字

由于我希望QPushButton超过QToolButton,因此我面临图标/文字对齐的已知问题(请参阅herehere)。

所以我的方法是专门化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");
    }
};

1 个答案:

答案 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位置,它显示如下:

The button when text "HelloWorld" painted at 0,0 location

所以,如果你看到,文字被绘制但是它超出了按钮的尺寸,因此你无法看到它。