在以下代码中,红色背景将在每个按键按下时来回跳转。添加更多标签(对我来说大约八个)会导致标签栏滚动按钮出现,并导致需要按下双标签键的情况。
有没有办法阻止滚动按钮获得键盘焦点?
# 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_())
答案 0 :(得分:1)
您可以通过在标签工具按钮上设置焦点政策来解决此问题:
class Widget(QtWidgets.QWidget):
...
def _add_tab(self, tabs):
...
for child in tabs.findChildren(QtWidgets.QToolButton):
child.setFocusPolicy(QtCore.Qt.NoFocus)