【问题标题】:PyQt5 custom QAction classPyQt5 自定义 QAction 类
【发布时间】:2016-08-13 08:02:22
【问题描述】:

为了减少混乱。我正在尝试生成我自己的继承自QAction 的类。从QMainWindow 我想调用重现以下代码:

class MainWindow(QMainWindow):

    def __init__(self):
        super().__init__()

        exitAction = QAction(QIcon('exit.png'), '&Exit', self)        
        exitAction.setShortcut('Ctrl+Q')
        exitAction.setStatusTip('Exit application')
        exitAction.triggered.connect(self.quit)

        menubar = self.menuBar()
        fileMenu = menubar.addMenu('&File')
        fileMenu.addAction(exitAction)

如您所见,我只是在菜单栏中添加一个操作。但我想让我的程序更加面向对象。我希望以下是可能的:

from PyQt5.QtWidgets import QAction
from PyQt5.QtGui import QIcon

class exitAction(QAction):

    def __init__(self,parent):
        super.__init__(QIcon('exit.png'), '&Exit', parent)
        self.setShortcut('Ctrl+Q')
        self.setStatusTip('Exit application')
        self.triggered.connect(parent.quit)

exitAction 类通过以下方式调用:

class MainWindow(QMainWindow):
     def __init__(self):

        #Create Menu
        self.menuBar = self.menuBar()

        #Add File Menu
        file_menu = self.menuBar.addMenu('&File')
        file_menu.addAction(exitAction(self))

这看起来很简单,但对我来说没有意义的是为什么近乎等效的代码本身就可以正常工作。

我得到的错误是TypeError: descriptor '__init__' requires a 'super' object but received a 'QIcon'。我给自己设置的问题也可能是对 python 的误解。如果我在 C++ 中工作,我只需传递一个引用 MainWindow 的指针。

【问题讨论】:

  • 顺便说一句,您可能会考虑在构造操作时使用关键字参数,而不是一遍又一遍地继承 QAction

标签: python c++ qt python-3.x pyqt


【解决方案1】:

我想你的问题在这里:

super.__init__(QIcon('exit.png'), '&Exit', parent)

你应该写super().而不是super.

【讨论】:

  • 哇,真是个愚蠢的错误。谢谢你。至少我知道代码可以以面向对象的方式编写。
猜你喜欢
  • 2019-08-02
  • 2021-11-22
  • 1970-01-01
  • 1970-01-01
  • 2014-11-17
  • 2021-07-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多