2012-11-12 85 views
3

我只是想設置一個PlaceHolderTextQTextEdit。我知道如何設置它爲QLineEdit。有一個屬性,setPlaceHolderText爲QLineEdit。但是這個屬性不適用於QTextEdit。請提出寶貴的建議來解決這個問題。如何設置QTextEdit的PlaceHolderText

+1

不像論壇網站,我們不使用「謝謝」或「任何幫助表示讚賞」,或在[so]上簽名。請參閱「[應該'嗨','謝謝',標語和致敬從帖子中刪除?](http://meta.stackexchange.com/questions/2950/should-hi-thanks-taglines-and-salutations-be -removed-from-posts)。 –

回答

3

使用setTextCursor(QTextCursor&)函數QTextEdit。使用以下邏輯。

QTextCursor textCursor; 
    textCursor.setPosistion(0, QTextCursor::MoveAnchor); 
    textedit->setTextCursor(textCursor); 
+0

你究竟是怎麼做到的? – swdev

0

我能夠子類化和重寫Paint事件要做到這一點:

class PlainTextEditWithPlaceholderText(QtGui.QPlainTextEdit): 
    def __init__(self, parent=None): 
     super(PlainTextEditWithPlaceholderText, self).__init__(parent) 
     self.placeholderText = "" # Qt-style camelCase 

    def setPlaceholderText(self, text): 
     self.placeholderText = text 

    def paintEvent(self, _event): 
     """ 
     Implements the same behavior as QLineEdit's setPlaceholderText() 
     Draw the placeholder text when there is no text entered and the widget 
     doesn't have focus. 
     """ 
     if self.placeholderText and not self.hasFocus() and not self.toPlainText(): 
      painter = QtGui.QPainter(self.viewport()) 

      color = self.palette().text().color() 
      color.setAlpha(128) 
      painter.setPen(color) 

      painter.drawText(self.geometry().topLeft(), self.placeholderText) 

     else: 
      super(PlainTextEditWithPlaceholderText, self).paintEvent(event)