【问题标题】:How to add QInputDialog.getText text inside a QGraphicsPolygonItem?如何在 QGraphicsPolygonItem 中添加 QInputDialog.getText 文本?
【发布时间】:2012-09-19 16:05:18
【问题描述】:

我在 PyQt4 中构建,但不知道如何将文本添加到 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()

【问题讨论】:

    标签: qt pyqt4


    【解决方案1】:

    好吧,你做得不对。你正在画一个QPicture (pic) 然后把它扔掉。

    我假设您想在 QGraphicsPolygonItem 上绘画。 QGraphicsItem(及其派生词)的paint 方法负责绘制项目。如果您想用该项目绘制额外的东西,您应该覆盖该方法并在那里进行绘制:

    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)
    

    【讨论】:

    • 谢谢,Avaris。在阅读了更多示例后,我最终发现了这一点。感谢您很好地总结了解决方案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多