Mat*_*son 5 python pyqt qtabwidget
我想检测QTabWidget上的鼠标中键.我期待在QWidget上有一个鼠标事件相关的信号,但我所看到的只是方法.
我是否需要继承QTabWidget,然后覆盖所述方法以便做我想要的,或者我错过了什么?
您可以安装在一个事件过滤器QTabBar(由返回QTabWidget.tabBar())来接收和处理按下和释放事件,或子类QTabBar重新定义mousePressEvent和mouseReleaseEvent和更换QTabBar的QTabWidget有QTabWidget.setTabBar().
使用事件过滤器的示例:
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
Run Code Online (Sandbox Code Playgroud)使用QTabBar子类的示例:
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
Run Code Online (Sandbox Code Playgroud)(如果你想知道为什么这么简单的任务有这么多的代码,点击被定义为一个按下事件,然后是大致相同点的一个发布事件,所以按下的标签的索引必须与发布标签).
| 归档时间: |
|
| 查看次数: |
4371 次 |
| 最近记录: |