简体   繁体   中英

Pyside Qt align QLabel proxy widget within QGraphicsItem

I would like to program a simple blocks scheme with rectangle objects, filled with some text. For the blocks I use a QGraphicsItem (parent) and the text in the rectangle is a proxy of a QLabel which is set up as a child of the QGraphicsItem.

class Node(QtGui.QGraphicsItem):
Type = QtGui.QGraphicsItem.UserType + 1

def __init__(self, scene, parent=None):
    QtGui.QGraphicsItem.__init__(self, scene=scene, parent=parent)

    self.setFlag(QtGui.QGraphicsItem.ItemIsMovable)
    self.setFlag(QtGui.QGraphicsItem.ItemSendsGeometryChanges)
    self.setCacheMode(self.DeviceCoordinateCache)
    self.setZValue(-1)

    self.width = 100
    self.height = 50

    textLabel = QtGui.QLabel('B1')
    textLabel.setAlignment(QtCore.Qt.AlignCenter) # This doesn't do shit
    proxyText = self.scene().addWidget(textLabel)
    proxyText.setParentItem(self)

I chose QLabel over QGraphicsSimpleTextItem because I should be able to set the alignment of the text for a label. But it doesn't work. The alignment is still Left|Up

Turns out, a simple geometry does the trick:

class Node(QtGui.QGraphicsItem):
    Type = QtGui.QGraphicsItem.UserType + 1

def __init__(self, scene, parent=None):
    QtGui.QGraphicsItem.__init__(self, scene=scene, parent=parent)

    self.setFlag(QtGui.QGraphicsItem.ItemIsMovable)
    self.setFlag(QtGui.QGraphicsItem.ItemSendsGeometryChanges)
    self.setCacheMode(self.DeviceCoordinateCache)
    self.setZValue(-1)

    self.width = 100
    self.height = 50

    textLabel = QtGui.QLabel('B1')
    textLabel.setAlignment(QtCore.Qt.AlignCenter) # This doesn't do shit on its own

    textLabel.setGeometry(
        -self.width / 2, 
        -self.height / 2, 
        self.width, 
        self.height) # It needs a frame of reference

    proxyText = self.scene().addWidget(textLabel)
    proxyText.setParentItem(self)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM