Reputation: 4626
In the following code the red background will jump back and forth with each tab-key press. Adding more tabs (around eight for me) causes the tab-bar scroll buttons to appear, and causes a situation where a double tab-key press will be required.
Is there any way to prevent the scroll buttons from getting the keyboard focus?
# Testing with python 3.6.3 pip installed pyqt5 5.9.2 in virtualenv on Ubuntu
import sys
from PyQt5 import QtCore, QtWidgets
class Widget(QtWidgets.QWidget):
def __init__(self, parent=None):
QtWidgets.QWidget.__init__(self, parent)
layout = QtWidgets.QVBoxLayout()
self.setLayout(layout)
self.tabs_left = QtWidgets.QTabWidget()
self.tabs_left.setFocusPolicy(QtCore.Qt.NoFocus)
self._add_tab(self.tabs_left)
self.tabs_right = QtWidgets.QTabWidget()
self.tabs_right.setFocusPolicy(QtCore.Qt.NoFocus)
self._add_tab(self.tabs_right)
layout.addWidget(self.tabs_left)
layout.addWidget(self.tabs_right)
self.add_button = QtWidgets.QPushButton('Add Tab')
self.add_button.setFocusPolicy(QtCore.Qt.NoFocus)
layout.addWidget(self.add_button)
self.add_button.clicked.connect(self._add_tab_left)
def _add_tab(self, tabs):
edit = QtWidgets.QTextEdit()
edit.setReadOnly(True)
edit.setStyleSheet("QTextEdit:focus { background-color: red;}")
tabs.addTab(edit, '{}'.format(tabs.count()))
def _add_tab_left(self):
self._add_tab(self.tabs_left)
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
widget = Widget()
widget.show()
sys.exit(app.exec_())
Upvotes: 1
Views: 912
Reputation: 120688
You can work around this by setting the focus-policy on the tab tool-buttons:
class Widget(QtWidgets.QWidget):
...
def _add_tab(self, tabs):
...
for child in tabs.findChildren(QtWidgets.QToolButton):
child.setFocusPolicy(QtCore.Qt.NoFocus)
Upvotes: 1