我已将QTableView
子类化为实现contextMenuEvent
。现在,如果我创建了子类的实例,则必须调用方法(如示例中的下面所示),而不是将它们作为关键字参数传递。但是,如果我不调用__init__
方法,它将接受关键字参数。
我无法弄清楚如何在实例化它时必须正确地继承QTableView
以便能够使用关键字参数。这个问题不仅涉及一般在子类化时如何使用功能,还在于了解其工作原理。
我通读了文档,并浏览了相关.pyi
文件的代码,但对我来说仍然不清楚。
示例:
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
data = ["file_name", "file_infos"]
class MyCustomTable(QTableView):
# if I don't call __init__ I'm able to use the
# keyword arguments below when instantiating the class
def __init__(self, parent):
super().__init__(parent)
def contextMenuEvent(self, event):
"""Create context menu, etc."""
class Ui_MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.init_ui()
def init_ui(self):
self.resize(450, 280)
centralwidget = QWidget(self)
# custom_table
custom_table = MyCustomTable(
centralwidget,
selectionBehavior=QAbstractItemView.SelectRows,
editTriggers=QAbstractItemView.NoEditTriggers,
sortingEnabled=True
)
#if instantiating my subclass of QTableView then I would
#have to call this methods instead of passing them as
#keyword arguments:
#self.setSelectionBehavior(QAbstractItemView.SelectRows)
#self.setEditTriggers(QAbstractItemView.NoEditTriggers)
#self.setSortingEnabled(True)
self.model = QStandardItemModel(0, 2, centralwidget)
self.model.setHorizontalHeaderLabels(["column 1", "column 2"])
custom_table.setModel(self.model)
v_layout1 = QVBoxLayout(centralwidget)
v_layout1.addWidget(custom_table)
self.setCentralWidget(centralwidget)
def populate_table(self):
self.model.setRowCount(0)
for item in data:
self.model.insertRow(0)
for i, text in enumerate(data):
self.model.setItem(0, i, QStandardItem(text))
if __name__ == "__main__":
import sys
app = QApplication(sys.argv)
mainUI = Ui_MainWindow()
mainUI.populate_table()
mainUI.show()
sys.exit(app.exec_())
输出:
Traceback (most recent call last):
File "/home/mvce/subclassing.py", line 28, in init_ui
custom_table = MyCustomTable(
TypeError: __init__() got an unexpected keyword argument 'selectionBehavior'
您需要捕获关键字参数或kwarg。这个答案应该有帮助:https://stackoverflow.com/a/1769475/6569951
MyCustomTable中的基本上,父是一个参数。如果需要任意数量的关键字参数,则需要在参数名称前使用**,例如** parent或** kwargs。