【问题标题】:Implementing a Canvas in PyQt5在 PyQt5 中实现画布
【发布时间】:2020-02-16 17:44:42
【问题描述】:

我一直在努力学习使用 PyQt5。

我想在“菜单栏”下面实现一个画布

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)

我的画布被定义为

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)

但对我来说,画布根本不渲染,更不用说椭圆了。

【问题讨论】:

  • 什么是圆?
  • 我相信我添加了一条评论,解释说... #circle 类创建一个圆心和半径都在 0 到 100 之间的随机圆

标签: python python-3.x pyqt pyqt5


【解决方案1】:

您不应该将 QMainWindow 用作画布,而应使用 QWidget。另一方面,如果您使用布局,setGeometry 将不起作用,因为后者处理几何图形,而是建立固定大小和足够的边距。另一方面,建议类的名称以大写字母开头,考虑到上述解决方案是:

class Canvas(QWidget):
    def __init__(self, parent=None):
        super(Canvas, self).__init__(parent)
        self.setFixedSize(1000, 700)
        self.setContentsMargins(100, 100, 100, 100)

    def paintEvent(self, e):
        # ...

【讨论】:

  • 我刚刚发现paintEvent只发生在事件上,我怎样才能根据需要设置一个绘图函数来绘制一个圆圈?
  • @Blaine 你必须调用 canvas update() 方法,尽管我认为你正在重新发明轮子:使用 QGraphicsView、QGraphicsScene 及其项目。
  • 你救了我的命!我想知道如何扩展 addEllipse 以在中心添加一个带有文本的圆圈,因为 addText 没有位置参数。
猜你喜欢
  • 2021-09-26
  • 2022-01-25
  • 2012-12-07
  • 1970-01-01
  • 1970-01-01
  • 2018-02-08
  • 1970-01-01
  • 2018-12-22
  • 2019-02-26
相关资源
最近更新 更多