【发布时间】: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