python - 防止按下 Tab 键时特定的 QLineEdit 聚焦

标签 python python-3.x pyqt5

我有一个 pyqt5 GUI。我想使用 Tab 键在 GUI 中导航。但我想防止特定的 QLineEdit 小部件在按下选项卡后获得焦点。我怎样才能做到这一点?

最佳答案

您可以设置所有控件都继承自的 QWidget 类中可用的属性 focusPolicy,例如:

import sys
from PyQt5.Qt import QApplication
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QIntValidator, QDoubleValidator
from PyQt5.QtWidgets import QWidget, QLineEdit, QFormLayout


class MainWindow(QWidget):
    def __init__(self):
        super().__init__()

        self.e1 = QLineEdit()
        self.e1.setValidator(QIntValidator())
        self.e1.setMaxLength(4)
        self.e1.setAlignment(Qt.AlignRight)

        # This control will focus using the tab key
        self.e1.setFocusPolicy(Qt.ClickFocus | Qt.TabFocus)

        e2 = QLineEdit()
        e2.setValidator(QDoubleValidator(0.99, 99.99, 2))

        # This control will not focus using the tab key
        e2.setFocusPolicy(Qt.ClickFocus | Qt.NoFocus)

        self.flo = QFormLayout()
        self.flo.addRow("integer validator", self.e1)
        self.flo.addRow("Double validator", e2)

        e3 = QLineEdit()
        e3.setInputMask('+99_9999_999999')
        self.flo.addRow("Input Mask", e3)

        # This control will not focus using the tab key
        e3.setFocusPolicy(Qt.ClickFocus | Qt.NoFocus)

        e4 = QLineEdit()
        self.flo.addRow("Text changed", e4)

        # This control will focus using the tab key (this is the default behaviour you don't need to explicitly set it)
        e4.setFocusPolicy(Qt.ClickFocus | Qt.TabFocus)

        # Default focus behaviour
        e5 = QLineEdit()
        e5.setEchoMode(QLineEdit.Password)
        self.flo.addRow("Password", e5)

        e6 = QLineEdit("Hello Python")
        e6.setReadOnly(True)
        self.flo.addRow("Read Only", e6)

        self.setLayout(self.flo)
        self.setWindowTitle("Example")


if __name__ == '__main__':
    app = QApplication(sys.argv)
    mainWindow = MainWindow()
    mainWindow.show()
    sys.exit(app.exec_())

更多信息请点击:https://doc.qt.io/qt-5/qwidget.html#focusPolicy-prop

关于python - 防止按下 Tab 键时特定的 QLineEdit 聚焦,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56197335/

相关文章:

python - 在python中的图像中的表格上创建边框

python - 比较大量图的同构性

python - 如何使用 PyGithub 在存储库中创建文件?

python - 如何从 python 宏读取 LibreOffice writer 注释的内容

python-3.x - 使用anytree和graphviz在python中渲染树,而不合并公共(public)节点

python - 在 Pandas 中折叠列和索引

python - PyQt如何从布局中移除布局

python - pyqt如何获取以前的无花果管理器

python - 魔法 python 不工作

python - 禁用 QWizardPage 的下一个按钮上的默认焦点,并让自定义 QPushButton 由 'enter' 触发