Prevent tab cycling with Ctrl+Tab by default with QTabWidget

帅比萌擦擦* 提交于 2021-02-10 23:48:06

问题


I have the following example code that makes a three tab layout (with buttons on the third tab). By default, I can Ctrl+Tab/Ctrl+Shift+Tab to cycle between the tabs. How do I disable this functionality? In my non-example code, this is not desired behaviour.

from PyQt4 import QtGui
import sys


def main():
    app = QtGui.QApplication(sys.argv)
    tabs = QtGui.QTabWidget()
    push_button1 = QtGui.QPushButton("QPushButton 1")
    push_button2 = QtGui.QPushButton("QPushButton 2")

    tab1 = QtGui.QWidget()
    tab2 = QtGui.QWidget()
    tab3 = QtGui.QWidget()

    vBoxlayout = QtGui.QVBoxLayout()
    vBoxlayout.addWidget(push_button1)
    vBoxlayout.addWidget(push_button2)
    tabs.resize(250, 150)
    tabs.move(300, 300)
    tab3.setLayout(vBoxlayout)

    tabs.addTab(tab1, "Tab 1")
    tabs.addTab(tab2, "Tab 2")
    tabs.addTab(tab3, "Tab 3")

    tabs.setWindowTitle('PyQt QTabWidget Add Tabs and Widgets Inside Tab')
    tabs.show()

    sys.exit(app.exec_())


if __name__ == '__main__':
    main()

回答1:


You can always install an eventFilter (similar to KeyPressEater here)

Here I did it:

from PySide import QtGui, QtCore

class AltTabPressEater(QtCore.QObject):
    def eventFilter(self, obj, event):
        if event.type() == QtCore.QEvent.KeyPress and (event.key() == 16777217 or event.key() == 16777218):
            return True # eat alt+tab or alt+shift+tab key
        else:
            # standard event processing
            return QtCore.QObject.eventFilter(self, obj, event)

app = QtGui.QApplication([])

tabs = QtGui.QTabWidget()
filter = AltTabPressEater()
tabs.installEventFilter(filter)
push_button1 = QtGui.QPushButton("QPushButton 1")
push_button2 = QtGui.QPushButton("QPushButton 2")

tab1 = QtGui.QWidget()
tab2 = QtGui.QWidget()
tab3 = QtGui.QWidget()

vBoxlayout = QtGui.QVBoxLayout()
vBoxlayout.addWidget(push_button1)
vBoxlayout.addWidget(push_button2)
tabs.resize(250, 150)
tabs.move(300, 300)
tab3.setLayout(vBoxlayout)

tabs.addTab(tab1, "Tab 1")
tabs.addTab(tab2, "Tab 2")
tabs.addTab(tab3, "Tab 3")

tabs.show()

app.exec_()

I was too lazy to find the right QtCore.Qt constants for the alt+tab or alt+shift+tab keys, so I just listened first and then replaced by what python told me.



来源:https://stackoverflow.com/questions/28417640/prevent-tab-cycling-with-ctrltab-by-default-with-qtabwidget

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