PyQt: How to catch mouse-over-event of QTableWidget-headers?

烈酒焚心 提交于 2020-01-06 18:13:10

问题


what I want to do is to change the text of a QLable, everytime I hover with the mouse over the horizontalHeaders of my QTableWidget. How can I do that? Everytime I'm over a new header I need a signal and the index of the header. Hope someone of you has an idea. There must be a function, because if you hover over the headers, the background of the header changes.


回答1:


Install an event filter that on the horizontalHeader() by using QObject.installEventFilter():

class HeaderViewFilter(QObject):
    # ...
    def eventFilter(self, object, event):
        if event.type() == QEvent.HoverEvent:
            pass # do something useful
            # you could emit a signal here if you wanted

self. filter = HeaderViewFilter()
horizontalHeader().installEventFilter(self.filter)

With self.filter in place, you'll be notified of the necessary events and can respond accordingly.

UPDATE: it looks like HoverEvent isn't quite what we need. In order to get hover events, you need to setAttribute needs to be called with Qt::WA_Hover. From the documentation on this attribute:

Forces Qt to generate paint events when the mouse enters or leaves the widget. This feature is typically used when implementing custom styles; see the Styles example for details.

So yes, it generates events only when you enter or leave the widget.

Since the same header is used for all rows or all columns, we'll actually want to know about where the mouse is within the widget. Here's some new code which should handle mouse moves:

class HeaderViewFilter(QObject):
    def __init__(self, parent, header, *args):
        super(HeaderViewFilter, self).__init__(parent, *args)
        self.header = header
    def eventFilter(self, object, event):
        if event.type() == QEvent.MouseMove:
            logicalIndex = self.header.logicalIndexAt(event.pos())
            # you could emit a signal here if you wanted

self.filter = HeaderViewFilter()
self.horizontalHeader = yourView.horizontalHeader()
self.horizontalHeader.setMouseTracking(1)
self.horizontalHeader.installEventFilter(self.filter)

As you can see above, the main concept still applies. We either need an event filter so that we can watch for events or we need to subclass QHeaderView so that it will provide us with the necessary information.



来源:https://stackoverflow.com/questions/3562447/pyqt-how-to-catch-mouse-over-event-of-qtablewidget-headers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!