Qheaderview 何时获得其模型?
When does Qheaderview get its model?
您可以使用 self.model() 访问 Headerview 的底层模型,但是当您在构造函数中使用它时它 returns None.
例如,这将打印 'None'
class MyHeaderView(QHeaderView):
def __init__(self, orientation, parent):
super().__init__(orientation, parent)
print(self.model())
Headerview 是在 QTableView 子类的构造函数中设置的,该子类当时已经设置了模型。
self.setHorizontalHeader(MyHeaderView(Qt.Horizontal, self))
所以它在构建的时候应该能知道它的模型是什么,但是好像不知道。当GUI为运行时,headerview的model可以正常访问
为什么会这样?该模型何时可用?
仅 parent 参数不足以设置模型(因为 parent 可以是任何类型的小部件,而不仅仅是项目视图),但按顺序添加它很重要使用小部件的样式、调色板、字体等正确地“初始化”它
仅当在视图上设置 header 时才实际设置模型(setHeader()
用于树视图,setHorizontalHeader()
和 setVerticalHeader()
用于表),但是 仅当 header上没有设置其他模型时。
当在视图上调用 setModel()
时再次设置模型,在这种情况下 any 以前的模型被替换为 [=29] 的新模型=]s.
如果您想对模型做一些事情(例如,当行或列为 added/removed/moved 时连接到自定义函数),您应该覆盖视图的 setModel()
:
class MyHeaderView(QHeaderView):
def setModel(self, newModel):
currentModel = self.model()
if currentModel == newModel:
return
elif currentModel:
currentModel.rowsInserted.disconnect(self.myFunction)
currentModel.rowsRemoved.disconnect(self.myFunction)
currentModel.rowsMoved.disconnect(self.myFunction)
super().setModel(newModel)
if newModel:
newModel.rowsInserted.connect(self.myFunction)
newModel.rowsRemoved.connect(self.myFunction)
newModel.rowsMoved.connect(self.myFunction)
def myFunction(self):
# do something
您可以使用 self.model() 访问 Headerview 的底层模型,但是当您在构造函数中使用它时它 returns None.
例如,这将打印 'None'
class MyHeaderView(QHeaderView):
def __init__(self, orientation, parent):
super().__init__(orientation, parent)
print(self.model())
Headerview 是在 QTableView 子类的构造函数中设置的,该子类当时已经设置了模型。
self.setHorizontalHeader(MyHeaderView(Qt.Horizontal, self))
所以它在构建的时候应该能知道它的模型是什么,但是好像不知道。当GUI为运行时,headerview的model可以正常访问
为什么会这样?该模型何时可用?
仅 parent 参数不足以设置模型(因为 parent 可以是任何类型的小部件,而不仅仅是项目视图),但按顺序添加它很重要使用小部件的样式、调色板、字体等正确地“初始化”它
仅当在视图上设置 header 时才实际设置模型(setHeader()
用于树视图,setHorizontalHeader()
和 setVerticalHeader()
用于表),但是 仅当 header上没有设置其他模型时。
当在视图上调用 setModel()
时再次设置模型,在这种情况下 any 以前的模型被替换为 [=29] 的新模型=]s.
如果您想对模型做一些事情(例如,当行或列为 added/removed/moved 时连接到自定义函数),您应该覆盖视图的 setModel()
:
class MyHeaderView(QHeaderView):
def setModel(self, newModel):
currentModel = self.model()
if currentModel == newModel:
return
elif currentModel:
currentModel.rowsInserted.disconnect(self.myFunction)
currentModel.rowsRemoved.disconnect(self.myFunction)
currentModel.rowsMoved.disconnect(self.myFunction)
super().setModel(newModel)
if newModel:
newModel.rowsInserted.connect(self.myFunction)
newModel.rowsRemoved.connect(self.myFunction)
newModel.rowsMoved.connect(self.myFunction)
def myFunction(self):
# do something