用于QWidget的QT paintEvent

时间:2014-01-18 16:03:51

标签: qt qwidget

我有一个继承QPushButton小部件的类。我想拥有该按钮的自定义外观,所以我已经覆盖了paintEvent方法。我要绘制的所有按钮都是QFrame对象的子项。

我有一个问题。我无法重绘那些物体。

我的paintEvent函数:

void Machine::paintEvent(QPaintEvent*) {
    QPainter painter(this);
    QRect geo = this->geometry();

    int x, y, width, height;

    x = geo.x()-10;
    y = geo.y()-10;
    width = geo.width()-3;
    height = geo.height()-5;

    painter.fillRect(x, y, width, height, QColor(220,220,220));

    painter.drawText(x+10, y+10, "Machine " + QString::number(id));
}

当小部件位于QFrame的左上角时,所需效果正常。但当我在其他地方移动按钮时,小部件开始消失。在图像上你可以看到发生了什么:

enter image description here

按钮刚刚向左移动了一些px。它为什么会这样? QFrame是该按钮的容器,足够大。

提前致谢;)

1 个答案:

答案 0 :(得分:4)

原因在于坐标系:geometry方法相对于父级返回位置,但QPainter::drawRect接受本地坐标中的矩形。试试这段代码:

void Machine::paintEvent(QPaintEvent*) {
    QPainter painter(this);

    int width = size().width() - 3;
    int height = size().height() - 5;

    painter.fillRect(0, 0, width, height, QColor(220,220,220));
    painter.drawText(10, 10, "Machine " + QString::number(id));
}
相关问题