2012-09-19 33 views
3

我在PyQt4中建立,並不知道如何將文本添加到QGraphicsPolygonItem。這個想法是在用戶雙擊後在矩形框的中間設置文本(並通過QInputDialog.getText獲取對話框)。如何在QGraphicsPolygonItem中添加QInputDialog.getText文本?

類是:

class DiagramItem(QtGui.QGraphicsPolygonItem): 
    def __init__(self, diagramType, contextMenu, parent=None, scene=None): 
     super(DiagramItem, self).__init__(parent, scene) 
     path = QtGui.QPainterPath() 
     rect = self.outlineRect() 
     path.addRoundRect(rect, self.roundness(rect.width()), self.roundness(rect.height())) 
     self.myPolygon = path.toFillPolygon() 

我的鼠標雙擊事件看起來是這樣,但更新什麼!

def mouseDoubleClickEvent(self, event): 
    text, ok = QtGui.QInputDialog.getText(QtGui.QInputDialog(),'Create Region Title','Enter Region Name: ', \ 
QtGui.QLineEdit.Normal, 'region name') 
    if ok: 
     self.myText = str(text) 
     pic = QtGui.QPicture() 
     qp = QtGui.QPainter(pic) 
     qp.setFont(QtGui.QFont('Arial', 40)) 
     qp.drawText(10,10,200,200, QtCore.Qt.AlignCenter, self.myText) 
     qp.end() 

回答

2

那麼,你做得不正確。您正在繪畫到QPicturepic)並將其扔掉。

我假設你想在上畫QGraphicsPolygonItempaint方法QGraphicsItem(及其衍生物)負責繪製物品。如果你想繪製物品的額外東西,你應該重寫該方法,並在那裏做你的畫:

class DiagramItem(QtGui.QGraphicsPolygonItem): 
    def __init__(self, diagramType, contextMenu, parent=None, scene=None): 
      super(DiagramItem, self).__init__(parent, scene) 
      # your `init` stuff 
      # ... 

      # just initialize an empty string for self.myText 
      self.myText = '' 

    def mouseDoubleClickEvent(self, event): 
     text, ok = QtGui.QInputDialog.getText(QtGui.QInputDialog(), 
                'Create Region Title', 
                'Enter Region Name: ', 
                QtGui.QLineEdit.Normal, 
                'region name') 
     if ok: 
      # you can leave it as QString 
      # besides in Python 2, you'll have problems with unicode text if you use str() 
      self.myText = text 
      # force an update 
      self.update() 

    def paint(self, painter, option, widget): 
     # paint the PolygonItem's own stuff 
     super(DiagramItem, self).paint(painter, option, widget) 

     # now paint your text 
     painter.setFont(QtGui.QFont('Arial', 40)) 
     painter.drawText(10,10,200,200, QtCore.Qt.AlignCenter, self.myText) 
+0

謝謝,Avaris。通過閱讀其他幾個例子,我發現了這個EVENTUALLY。非常感謝您總結解決方案。 – seanlorenz