PySide QPainter.drawRect() 与 QBrush 偏移问题
PySide QPainter.drawRect() with QBrush offset issue
我正在尝试绘制尺寸为 20x20 像素的自定义按钮。我创建了一个继承 QPushButton 的 class,我用下面的代码覆盖了 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)
这就是我得到的(在 Photoshop 中编辑):
您可以清楚地看到左上角在 x 和 y 维度上都有 1 个像素的偏移。
我想知道为什么会这样。我可以通过从 x 和 y 中提取 1 个像素并将宽度和高度添加 1 个像素来摆脱它,因此它们的值将是:x = -1; y = -1;宽度 = 21;高度 = 21.
但这让我觉得很奇怪。我不知道这是 Qt(或者可能只是 PySide)的问题还是我不明白。
我认为您对 QPainter::drawRect
的实际作用感到困惑。来自 QPainter documentation
Draws the current rectangle with the current pen and brush.
矩形用当前画笔填充,用当前画笔勾勒轮廓。考虑到这一点,我怀疑当你打电话给 QPainter::drawRect
时,你有一支笔正在为画家激活,导致你看到灰色轮廓。
如果您只想填充矩形,那么您可以使用...
painter = QtGui.QPainter(self)
painter.fillRect(this->rect(), QBrush(QColor(170, 97, 112)))
我正在尝试绘制尺寸为 20x20 像素的自定义按钮。我创建了一个继承 QPushButton 的 class,我用下面的代码覆盖了 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)
这就是我得到的(在 Photoshop 中编辑):
您可以清楚地看到左上角在 x 和 y 维度上都有 1 个像素的偏移。
我想知道为什么会这样。我可以通过从 x 和 y 中提取 1 个像素并将宽度和高度添加 1 个像素来摆脱它,因此它们的值将是:x = -1; y = -1;宽度 = 21;高度 = 21.
但这让我觉得很奇怪。我不知道这是 Qt(或者可能只是 PySide)的问题还是我不明白。
我认为您对 QPainter::drawRect
的实际作用感到困惑。来自 QPainter documentation
Draws the current rectangle with the current pen and brush.
矩形用当前画笔填充,用当前画笔勾勒轮廓。考虑到这一点,我怀疑当你打电话给 QPainter::drawRect
时,你有一支笔正在为画家激活,导致你看到灰色轮廓。
如果您只想填充矩形,那么您可以使用...
painter = QtGui.QPainter(self)
painter.fillRect(this->rect(), QBrush(QColor(170, 97, 112)))