簡體   English   中英

PyQt5自定義QAction類

[英]PyQt5 custom QAction class

為了減少混亂。 我試圖產生自己的類,該類繼承自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.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM