我想在QTabWidget上检测鼠标中键单击事件。我本以为QWidget上会有与鼠标事件相关的信号,但我看到的都是方法。
我需要继承QTabWidget并重载相关方法才能做到我想要的吗?还是我漏掉了什么?
我想在QTabWidget上检测鼠标中键单击事件。我本以为QWidget上会有与鼠标事件相关的信号,但我看到的都是方法。
我需要继承QTabWidget并重载相关方法才能做到我想要的吗?还是我漏掉了什么?
您可以在 QTabWidget.tabBar()
返回的 QTabBar
上安装一个事件过滤器来接收和处理按下和释放事件,或者子类化 QTabBar
来重新定义 mousePressEvent
和 mouseReleaseEvent
并使用 QTabWidget.setTabBar()
方法替换 QTabWidget
的 QTabBar
。
Example using the event filter:
class MainWindow(QMainWindow):
def __init__(self):
super(QMainWindow,self).__init__()
self.tabWidget = QTabWidget(self)
self.setCentralWidget(self.tabWidget)
self.tabWidget.tabBar().installEventFilter(self)
self.tabWidget.tabBar().previousMiddleIndex = -1
def eventFilter(self, object, event):
if object == self.tabWidget.tabBar() and \
event.type() in [QEvent.MouseButtonPress,
QEvent.MouseButtonRelease] and \
event.button() == Qt.MidButton:
tabIndex = object.tabAt(event.pos())
if event.type() == QEvent.MouseButtonPress:
object.previousMiddleIndex = tabIndex
else:
if tabIndex != -1 and tabIndex == object.previousMiddleIndex:
self.onTabMiddleClick(tabIndex)
object.previousMiddleIndex = -1
return True
return False
# function called with the index of the clicked Tab
def onTabMiddleClick(self, index):
pass
Example using a QTabBar subclass:
class TabBar(QTabBar):
middleClicked = pyqtSignal(int)
def __init__(self):
super(QTabBar, self).__init__()
self.previousMiddleIndex = -1
def mousePressEvent(self, mouseEvent):
if mouseEvent.button() == Qt.MidButton:
self.previousIndex = self.tabAt(mouseEvent.pos())
QTabBar.mousePressEvent(self, mouseEvent)
def mouseReleaseEvent(self, mouseEvent):
if mouseEvent.button() == Qt.MidButton and \
self.previousIndex == self.tabAt(mouseEvent.pos()):
self.middleClicked.emit(self.previousIndex)
self.previousIndex = -1
QTabBar.mouseReleaseEvent(self, mouseEvent)
class MainWindow(QMainWindow):
def __init__(self):
super(QMainWindow,self).__init__()
self.tabWidget = QTabWidget(self)
self.setCentralWidget(self.tabWidget)
self.tabBar = TabBar()
self.tabWidget.setTabBar(self.tabBar)
self.tabBar.middleClicked.connect(self.onTabMiddleClick)
# function called with the index of the clicked Tab
def onTabMiddleClick(self, index):
pass
object == self.tabWidget.tabBar()
,那么这个表达式真的需要括号吗? - DanieltabBar()
是一个函数调用。 - alexisdm