2012-09-01 25 views
5

我試圖創建一個TextEdit小部件,它具有一個分隔符行。作爲一個開始,我創建了一個MyTextEdit類(爲QTextEdit的一個子類),並覆蓋其paintEvent()方法:在PyQt中重寫QPaintEvents

import sys 
from PyQt4.QtGui import QApplication, QTextEdit, QPainter 

class MyTextEdit(QTextEdit): 
    """A TextEdit widget derived from QTextEdit and implementing its 
     own paintEvent""" 

    def paintEvent(self, event): 
     painter = QPainter(self) 
     painter.drawLine(0, 10, 10, 10) 
     QTextEdit.paintEvent(self, event) 

app = QApplication(sys.argv) 
textEdit = MyTextEdit() 
textEdit.show() 

sys.exit(app.exec_()) 

嘗試,我得到很多下面的錯誤執行此代碼:

QPainter::begin: Widget painting can only begin as a result of a paintEvent 
QPainter::begin: Widget painting can only begin as a result of a paintEvent 
... 

我在做什麼錯?

回答

7

如果一個部件有一個viewport,你必須傳遞到QPainter構造:

painter = QPainter(self.viewport()) 
+0

有趣,是啊,我無法弄清楚,爲什麼這是行不通的。那個視口總是把我搞砸了。謝謝! –