如何防止QTabWidget 滚动按钮获得焦点?
How to prevent QTabWidget scroll buttons from gaining focus?
在下面的代码中,红色背景会随着每次按下 tab 键来回跳动。添加更多选项卡(对我来说大约八个)会导致出现选项卡栏滚动按钮,并导致需要按两次 Tab 键的情况。
有什么方法可以防止滚动按钮获得键盘焦点吗?
# 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_())
您可以通过在选项卡工具按钮上设置焦点策略来解决此问题:
class Widget(QtWidgets.QWidget):
...
def _add_tab(self, tabs):
...
for child in tabs.findChildren(QtWidgets.QToolButton):
child.setFocusPolicy(QtCore.Qt.NoFocus)
在下面的代码中,红色背景会随着每次按下 tab 键来回跳动。添加更多选项卡(对我来说大约八个)会导致出现选项卡栏滚动按钮,并导致需要按两次 Tab 键的情况。
有什么方法可以防止滚动按钮获得键盘焦点吗?
# 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_())
您可以通过在选项卡工具按钮上设置焦点策略来解决此问题:
class Widget(QtWidgets.QWidget):
...
def _add_tab(self, tabs):
...
for child in tabs.findChildren(QtWidgets.QToolButton):
child.setFocusPolicy(QtCore.Qt.NoFocus)