QPixmap / QPainter 显示黑色 window 背景
QPixmap / QPainter showing black window background
我正在按照 Martin Fitzpatrick 的 PyQt5 书中的示例进行操作。当我运行下面的代码时,背景是黑色的,没有画线:
import sys
from PyQt5 import QtCore, QtGui, QtWidgets, uic
from PyQt5.QtCore import Qt
class MainWindow(QtWidgets.QMainWindow):
def __init__(self):
super().__init__()
self.label = QtWidgets.QLabel()
canvas = QtGui.QPixmap(400, 300)
self.label.setPixmap(canvas)
self.setCentralWidget(self.label)
self.draw_something()
def draw_something(self):
painter = QtGui.QPainter(self.label.pixmap())
painter.drawLine(10, 10, 300, 200)
painter.end()
app = QtWidgets.QApplication(sys.argv)
window = MainWindow()
window.show()
app.exec_()
左边是预期的结果:
默认情况下,QPixmap 使用的内存不会被效率清理,因此它的字节不会被更改,如 the docs 所示:
QPixmap::QPixmap(int width, int height)
Constructs a pixmap with the
given width and height. If either width or height is zero, a null
pixmap is constructed.
Warning: This will create a QPixmap with uninitialized data. Call
fill() to fill the pixmap with an appropriate color before drawing
onto it with QPainter.
(强调我的)
解决方法是使用fill来设置背景色:
canvas = QtGui.QPixmap(400, 300)
canvas.fill(QtGui.QColor("white"))
我正在按照 Martin Fitzpatrick 的 PyQt5 书中的示例进行操作。当我运行下面的代码时,背景是黑色的,没有画线:
import sys
from PyQt5 import QtCore, QtGui, QtWidgets, uic
from PyQt5.QtCore import Qt
class MainWindow(QtWidgets.QMainWindow):
def __init__(self):
super().__init__()
self.label = QtWidgets.QLabel()
canvas = QtGui.QPixmap(400, 300)
self.label.setPixmap(canvas)
self.setCentralWidget(self.label)
self.draw_something()
def draw_something(self):
painter = QtGui.QPainter(self.label.pixmap())
painter.drawLine(10, 10, 300, 200)
painter.end()
app = QtWidgets.QApplication(sys.argv)
window = MainWindow()
window.show()
app.exec_()
左边是预期的结果:
默认情况下,QPixmap 使用的内存不会被效率清理,因此它的字节不会被更改,如 the docs 所示:
QPixmap::QPixmap(int width, int height)
Constructs a pixmap with the given width and height. If either width or height is zero, a null pixmap is constructed.
Warning: This will create a QPixmap with uninitialized data. Call fill() to fill the pixmap with an appropriate color before drawing onto it with QPainter.
(强调我的)
解决方法是使用fill来设置背景色:
canvas = QtGui.QPixmap(400, 300)
canvas.fill(QtGui.QColor("white"))