2012-09-07 131 views
1

我是Python新手,使用PyQt4開發Gui。我想在按下切換按鈕的同時更改圓圈的顏色。但我得到了插槽中的錯誤。Python PyQt:TypeError,同時按下按鈕來改變圓的顏色

我的代碼是:

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_() 

回答

3

它所代表的方式,它試圖調用changecolor只有一個說法,自我。我不完全確定你想要達到的目標。你的changecolor需要一個變量「paint」,但是試圖使用self.paint,它不存在。因此,也許你會想,你可以得到畫家的保持與一個呼叫QPainter的,失去所謂的「漆」的參數,如下列:

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_() 
+0

感謝丹尼爾,它解決了這個問題 – mrtak

+0

丹尼爾,我已經改變,從簡單的按鈕的代碼切換按鈕(如上在我的崗位代碼,請看看代碼)並且想要在按下時改變我的圈子的顏色,我嘗試了很多組合,但無法解決問題,請告訴我如何解決它。 – mrtak

+0

你會得到什麼樣的錯誤? 「插槽中的錯誤」並不是真正的描述。此外,我認爲你不應該做你剛剛做的事情,即在得到答案後改變問題。修改問題使其更加清晰,反映瞭解決方案中的進一步嘗試等等,都很好,但是現在您已經改變了問題,並且現在的答案並不適用於問題。我覺得開始一個新問題會更好,因爲現在你有一個新的問題。 –

相關問題