简体   繁体   English

PySide QPainter.drawRect()与QBrush偏移量问题

[英]PySide QPainter.drawRect() with QBrush offset issue

I'm trying to draw my custom push button which has dimensions 20x20 pixels. 我正在尝试绘制尺寸为20x20像素的自定义按钮。 I created a class that inherits QPushButton and I have overwritten paintEvent method with this code below: 我创建了一个继承QPushButton的类,并使用以下代码覆盖了paintEvent方法:

painter = QtGui.QPainter(self)

x = self.rect().x()
y = self.rect().y()

width = self.rect().width()
height = self.rect().height()

painter.setBrush(QBrush(QColor(170, 97, 112)))
painter.drawRect(x, y, width, height)

And this is what I get (edited in Photoshop): 这就是我得到的(在Photoshop中编辑):

在此处输入图片说明

You can clearly see 1 pixel offset both in x, and y dimensions on the top left. 您可以在左上方的x和y尺寸中清楚地看到1个像素偏移。

I was wondering why this is happening. 我想知道为什么会这样。 I can get rid of this by extracting 1 pixel from x, and y and adding 1 pixel to width and height, so their value will be: x = -1; 我可以通过从x和y提取1个像素并在宽度和高度上添加1个像素来摆脱这种情况,因此它们的值将是:x = -1; y = -1; y = -1; width = 21; 宽度= 21; height = 21. 高度= 21。

But this just feels wierd to me. 但这对我来说感觉很奇怪。 I don't know if this is an issue with Qt (or maybe just PySide) or I don't understand something. 我不知道这是Qt的问题(也许只是PySide),还是我听不懂。

I think your getting confused about what QPainter::drawRect actually does. 我认为您对QPainter::drawRect实际作用感到困惑。 From the QPainter documentation QPainter文档

Draws the current rectangle with the current pen and brush. 使用当前的笔和画笔绘制当前的矩形。

The rectangle is filled with the current brush and outlined with the current pen. 矩形将填充当前的笔刷,并使用当前的笔画轮廓。 With that in mind I suspect that when you call QPainter::drawRect you have a pen active for the painter causing the grey outline you see. 考虑到这一点,我怀疑当您调用QPainter::drawRect ,有一支为绘画者激活的笔会导致您看到灰色轮廓。

If all you want is to fill the rectangle then you can use... 如果您要填充的是矩形,则可以使用...

painter = QtGui.QPainter(self)
painter.fillRect(this->rect(), QBrush(QColor(170, 97, 112)))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM