单击按钮时在pyqt5窗口中添加圆的代码
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow,QPushButton,QWidget
from PyQt5 import QtGui
from PyQt5.QtCore import QRect,Qt
from PyQt5.QtGui import QPainter,QBrush, QPen
from PyQt5 import QtCore
class Window(QMainWindow):
def __init__(self):
super().__init__()
title="layout management"
left=500
top=200
width=500
height=400
iconName="fosseeicon.jpg"
self.setWindowTitle(title)
self.setWindowIcon(QtGui.QIcon(iconName))
self.setGeometry(left, top, width, height)
self.windowcomponents()
self.show()
def windowcomponents(self):
button=QPushButton("Add", self)
button.setGeometry(QRect(0, 0, 50, 28))
button.setIcon(QtGui.QIcon("addbutton.png"))
button.setToolTip("<h3>This is for creating random circles<h3>")
button.clicked.connect(self.paintcircle)
button=QPushButton("Generate Report", self)
button.setGeometry(QRect(49,0,150,28))
button.setIcon(QtGui.QIcon("generatereport.png"))
button.setToolTip("This is for generating pdf report of connection between two circles")
button=QPushButton("Save", self)
button.setGeometry(QRect(199,0,120,28))
button.setIcon(QtGui.QIcon("saveicon.png"))
button.setToolTip("This is for saving an image of canvas area")
def paintcircle(self, event):
painter.begin(self)
painter.setRenderHint(QPainter.Antialiasing)
painter.setPen(QPen(Qt.black, 5, Qt.SolidLine))
painter.drawEllipse(100, 100, 100, 100)
app = QApplication(sys.argv)
ex = Window()
circle=paintcircle()
circle.show()
sys.exit(app.exec_())
在这里,我得到了许多错误:
*Traceback (most recent call last):
File "<input>", line 1, in <module>
File "C:\Program Files\JetBrains\PyCharm Community Edition 2019.3.3\plugins\python-ce\helpers\pydev\_pydev_bundle\pydev_umd.py", line 197, in runfile
pydev_imports.execfile(filename, global_vars, local_vars) # execute the script
File "C:\Program Files\JetBrains\PyCharm Community Edition 2019.3.3\plugins\python-ce\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in execfile
exec(compile(contents+"\n", file, 'exec'), glob, loc)
File "C:/Users/DishaKhattri/PycharmProjects/helloworld/helloworld.py", line 45, in <module>
circle=paintcircle()
NameError: name 'paintcircle' is not defined*
如果您想在小部件上绘制额外的形状,通常的方法是覆盖
paintEvent
,创建一个QPainter
对象,并使用此画师绘制所需的形状。在您的情况下,由于您只希望在某些情况下绘制圆,因此可以使用标志指示是否应绘制圆,并且仅在该标志为真时在paintEvent
中绘制圆,例如相关问题 更多 >
编程相关推荐