1

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

hasdrubal
  • 1,024
  • 14
  • 30

1 Answers1

1

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)
hasdrubal
  • 1,024
  • 14
  • 30