问题
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