我是Python新手,使用PyQt4开发Gui。我想在按下切换按钮的同时更改圆圈的颜色。但是我在插槽中收到了错误。
我的代码是:
import sys
from PyQt4.QtGui import *
from PyQt4.QtCore import *
class MyFrame(QWidget):
def __init__(self, parent=None):
QWidget.__init__(self)
self.scene=QGraphicsScene(self)
self.scene.setSceneRect(QRectF(0,0,245,245))
self.bt=QPushButton("Press",self)
self.bt.setGeometry(QRect(450, 150, 90, 30))
self.bt.setCheckable(True)
self.color = QColor(Qt.green)
self.color1= QColor(Qt.magenta)
self.show()
self.connect(self.bt, SIGNAL("clicked()"), self.changecolor)
def paintEvent(self, event=None):
paint=QPainter(self)
paint.setPen(QPen(QColor(Qt.magenta),1,Qt.SolidLine))
paint.setBrush(self.color)
paint.drawEllipse(190,190, 70, 70)
paint.setPen(QPen(QColor(Qt.green),1,Qt.SolidLine))
paint.setBrush(self.color1)
paint.drawEllipse(300,300, 70, 70)
def changecolor(self):
if pressed:
self.color = QColor(Qt.red)
self.color1= QColor(Qt.blue)
else:
self.color=QColor(Qt.yellow)
self.color1=QColor(Qt.gray)
self.update()
app=QApplication(sys.argv)
f=MyFrame()
f.show()
app.exec_()
答案 0 :(得分:3)
它的方式,它试图只用一个参数self来调用changecolor。我不完全确定你想要实现的目标。你的changecolor接受一个变量“paint”,但尝试使用self.paint,它不存在。所以也许你可以想一想,你可以通过调用QPainter来获取画家,并丢失一个名为“paint”的参数,如下所示:
def changecolor(self):
paint = QPainter(self)
paint.setBrush(QColor(Qt.red))
paint.drawEllipse(190,190,70,70)
self.update()
这会遇到以下错误:
QPainter::begin: Widget painting can only begin as a result of a paintEvent
QPainter::setBrush: Painter not active
告诉你,你只能在paintEvent中有绘画动作。一种解决方案是拥有一个类成员,例如self.color,用于保存圆圈所需的颜色。完整工作的代码如下:
import sys
from PyQt4.QtGui import *
from PyQt4.QtCore import *
class MyFrame(QWidget):
def __init__(self, parent=None):
QWidget.__init__(self)
self.scene=QGraphicsScene(self)
self.scene.setSceneRect(QRectF(0,0,245,245))
self.bt=QPushButton("Press",self)
self.bt.setGeometry(QRect(450, 150, 90, 30))
self.color = QColor(Qt.green)
self.show()
self.connect(self.bt, SIGNAL("clicked()"), self.changecolor)
def paintEvent(self, event=None):
paint=QPainter(self)
paint.setPen(QPen(QColor(Qt.red),1,Qt.SolidLine))
paint.setBrush(self.color)
paint.drawEllipse(190,190, 70, 70)
def changecolor(self):
self.color = QColor(Qt.red)
self.update()
app=QApplication(sys.argv)
f=MyFrame()
f.show()
app.exec_()