The problem with the QAction signal of the right-click menu when using pyqt5

When using pyqt5 to write the right-click menu, there is a problem with the slot function and signal connection of Action.

# 创建右键菜单    
def show_context_menu(self):
        self.context_menu = QMenu(self)
        self.add_action = QAction("新增")
        self.delete_action = QAction("删除")
        self.context_menu.addAction(self.add_action)
        self.context_menu.addAction(self.delete_action)
        # 声明当鼠标在groupBox控件上右击时,在鼠标位置显示右键菜单只能用popup,exec/exec_两个都不行
        self.context_menu.exec(QCursor.pos())
        # 选中行数/列数
        select_size = len(self.tableView.selectionModel().selection().indexes())
        print("选中行数:" + str(select_size))
        for index in self.tableView.selectionModel().selection().indexes():
            row, column = index.row(), index.column()
            print(f"当前选中第{row},第{column}列")
        self.add_action.triggered.connect(self.add_service())
        self.delete_action.triggered.connect(self.remove_service)

have to be aware of is 

self.context_menu.exec(QCursor.pos()) code. self.context_menu has exec/exec_/popup method

If exec/exec_ is used, the following connection function (slot function) needs to be parenthesized, and the slot function needs to be parenthesized. Otherwise the slot function is not executed, however the slot function will be connected twice . The final error is as follows

Traceback (most recent call last):
  File "C:\Users\yingxu.zhao\PycharmProjects\ci-helper\gui\config_table.py", line 61, in show_context_menu
    self.add_action.triggered.connect(self.add_service())
TypeError: argument 1 has unexpected type 'NoneType'

 

Therefore, the correct use should be to use the popup method.

The correct code is as follows

  # 创建右键菜单
    def show_context_menu(self):
        self.context_menu = QMenu(self)
        self.add_action = QAction("新增")
        self.delete_action = QAction("删除")
        self.context_menu.addAction(self.add_action)
        self.context_menu.addAction(self.delete_action)
        # 声明当鼠标在groupBox控件上右击时,在鼠标位置显示右键菜单只能用popup,exec/exec_两个都不行
        self.context_menu.popup(QCursor.pos())
        # 选中行数/列数
        select_size = len(self.tableView.selectionModel().selection().indexes())
        print("选中行数:" + str(select_size))
        for index in self.tableView.selectionModel().selection().indexes():
            row, column = index.row(), index.column()
            print(f"当前选中第{row},第{column}列")
        self.add_action.triggered.connect(self.add_service)
        # 如果需要传递参数
        self.delete_action.triggered.connect(lambda: self.remove_service(row))

 

Guess you like

Origin blog.csdn.net/kanyun123/article/details/116884201