简体   繁体   中英

When does Qheaderview get its model?

You can access the underlying model of a Headerview with self.model(), but when you use this in the constructor it returns None.

For example, this will print 'None'

class MyHeaderView(QHeaderView):

    def __init__(self, orientation, parent):
        super().__init__(orientation, parent)
        print(self.model())

The Headerview is set in the constructor of a QTableView subclass, which at that time already has its model set.

self.setHorizontalHeader(MyHeaderView(Qt.Horizontal, self))

So it should be able to know what its model is during construction, but it doesn't seem to. When the GUI is running, the model of the headerview can be accessed without problems.

Why does this happen? and When does the model become available?

The parent argument alone is not enough to set the model (since the parent could be any kind of widget, not only an item view), but it's important to add it in order to properly "initialize" it with the widget's style, palette, font, etc.

The model is actually set only when the header is set on the view ( setHeader() for tree views, setHorizontalHeader() and setVerticalHeader() for tables), but only if no other model is already set on the header.

The model is again set when setModel() is called on the view, and in this case any previous model is replaced with the new one for the headers.

If you want to do something with the model (for instance, connect to a custom function when rows or columns are added/removed/moved), you should override setModel() of the view:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM