我一直在尝试学习使用 PyQt5。
我想在“菜单栏”下方实现一个 Canvas
class gui(QDialog):
def __init__(self, parent=None):
super(gui, self).__init__(parent)
self.createTopLayout()
self.painter = canvas(self)
mainLayout = QGridLayout()
mainLayout.addLayout(self.topLayout, 0, 0, 1, 2)
mainLayout.addWidget(self.painter, 1, 0, 6, 2)
self.setLayout(mainLayout)
def createTopLayout(self):
self.topLayout = QHBoxLayout()
button1 = QPushButton("b1")
button2 = QPushButton("b2")
button3 = QPushButton("b3")
styleComboBox = QComboBox()
styleComboBox.addItems(QStyleFactory.keys())
styleLabel = QLabel("&Style:")
styleLabel.setBuddy(styleComboBox)
self.topLayout.addWidget(styleLabel)
self.topLayout.addWidget(styleComboBox)
self.topLayout.addStretch(1)
self.topLayout.addWidget(button1)
self.topLayout.addWidget(button2)
self.topLayout.addWidget(button3)
我的 Canvas 定义为
class canvas(QMainWindow):
def __init__(self, parent=None):
super(canvas, self).__init__(parent)
self.setGeometry(100, 100, 1000, 700)
def paintEvent(self, e):
cir = circle() #circle class creates a circle with random center and radius both between 0 to 100
painter = QPainter(self)
painter.setPen(QPen(Qt.red, 1, Qt.SolidLine))
painter.drawEllipse(self, cir.center.x, cir.center.y, cir.radius, cir.radius)
但对我来说, Canvas 根本不渲染,更不用说椭圆了。
最佳答案
您不应该使用 QMainWindow 作为 Canvas ,而应使用 QWidget。另一方面,如果您使用布局,setGeometry 将不起作用,因为后者处理几何图形,而是建立固定的大小和足够的边距。另一方面,建议类的名称以大写字母开头,考虑到上述解决方案是:
class Canvas(<b>QWidget</b>):
def __init__(self, parent=None):
super(Canvas, self).__init__(parent)
<b>self.setFixedSize(1000, 700)
self.setContentsMargins(100, 100, 100, 100)</b>
def paintEvent(self, e):
# ...
关于python - 在 PyQt5 中实现 Canvas ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60251337/