gpt4 book ai didi

python - PyQt5 自定义 QAction 类

转载 作者:行者123 更新时间:2023-11-28 05:43:02 30 4
gpt4 key购买 nike

努力减少困惑。我正在尝试生成我自己的继承自 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 的指针。

最佳答案

我想你的问题在这里:

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

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

关于python - PyQt5 自定义 QAction 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36747242/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com