【问题标题】:Checking which item is on focus with QGraphicsItem.focusItem()使用 QGraphicsItem.focusItem() 检查哪个项目是焦点
【发布时间】:2022-01-11 12:21:27
【问题描述】:

所以这是我正在做的这个练习,每当我单击“create_button”时,我需要在 QGraphicsScene 中创建正方形,当我单击任何正方形时,该正方形的名称应该显示在 QLabel 中,即在 QGraphicsView 下,这就是我尝试这样做的方式。

这是我使用的窗口

这是代码

    
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()

但是,当我运行此代码时,我收到以下错误:

# Error: TypeError: file <maya console> line 32: descriptor 'focusItem' of 'PySide2.QtWidgets.QGraphicsItem' object needs an argument # 

说实话,我真的不明白我应该在 focusItem() 中传递什么参数,这就是问题所在。我认为它不需要任何参数,因为它应该返回当前关注的任何可悲的对象。 这可能是一个小问题,但它现在真的放慢了我的步伐,所以如果有人可以提供帮助,我将非常感激:)

【问题讨论】:

    标签: python pyqt5 qgraphicsview qgraphicsscene qgraphicsitem


    【解决方案1】:

    您不尊重信号QGraphicsScene::focusItemChanged。您必须将其连接到接收这些参数的函数:

    def nameDisplay(self, newFocusItem, oldFocusItem, reason):
        # ...presumably use newFocusItem
    

    也写错了:

    self.current_focus_obj = QGraphicsItem.focusItem()
    

    因为该函数不是静态的。它必须在 QGraphicsItem 的实例上调用。

    【讨论】:

    • 请注意,我对current_focus_obj 的评论与正确使用该功能有关。该代码不是解决您的问题所必需的,您只需处理 nameDisplay 中的焦点项目即可。
    • @galaxy 如果可行,请不要将其写在 cmets 中,尤其是因为它们不支持格式化。除此之外,正如 Passerby 已经说过的那样,那行是错误的,因为 QGraphicsItem.focusItem() 如果这样写是无效的:focusItem 不是静态或类方法,它需要一个实例。如果您不理解某些内容(或只是询问),请更仔细阅读所解释的内容并研究该主题。
    • @musicamante 好的,谢谢
    猜你喜欢
    • 2016-04-24
    • 2017-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-29
    • 2023-03-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多