So here's this exercise I'm doing, where I need to create squares in a QGraphicsScene whenever I click "create_button" and when I click on any of the squares the name of that square should be displayed in a QLabel, which is under the QGraphicsView, and here's how I'm trying to do that.
This is the window that I use
and here's the code
class rectangles(QtWidgets.QDialog):
def __init__(self):
super(rectangles, self).__init__()
loader = QtUiTools.QUiLoader()
self.ui = loader.load(ui_path, self)
self.variables()
self.ui.create_button.clicked.connect(self.creator)
self.scene.focusItemChanged.connect(self.nameDisplay)
def variables(self):
self.scene = QtWidgets.QGraphicsScene()
self.ui.canvas_area.setScene(self.scene)
self.current_focus_obj = QGraphicsItem.focusItem() #the problem is in here
def creator(self):
rect = self.scene.addRect(-20,-20,40,40, QPen(Qt.red), QBrush(Qt.gray))
rect.setFlag(QGraphicsItem.ItemIsMovable)
rect.setFlag(QGraphicsItem.ItemIsFocusable)
rect.setFlag(QGraphicsItem.ItemIsSelectable)
num_list.remove(num_list[0])
def nameDisplay(self):
self.ui.name_line.setText(str(self.current_focus_obj)) #Here I try to set
#the name of the
#active rectangle
#to my QLabel
if __name__ == '__main__':
rectangles_window = rectangles()
rectangles_window.ui.show()
However, when I run this code I get the following error:
# Error: TypeError: file <maya console> line 32: descriptor 'focusItem' of 'PySide2.QtWidgets.QGraphicsItem' object needs an argument #
To be honest, I don't really understand what argument I should pass in focusItem() and that's what the problem is. I thought it didn't need any arguments as it should return any abject that is currently on focus. This might be a small problem but it's really slowing down my pace right now, so if someone could help I would really appreciate that:)
You aren't respecting the signal QGraphicsScene::focusItemChanged. You have to connect it to a function that receives those parameters:
def nameDisplay(self, newFocusItem, oldFocusItem, reason):
# ...presumably use newFocusItem
It is also wrong to write:
self.current_focus_obj = QGraphicsItem.focusItem()
because that function is not static. It must be called on an instance of QGraphicsItem
.