如何避免在 PySide 中同时出现多个焦点?

How do I avoid multiple simultaneous focus in PySide?

我有一个 QDialog,它有多个 QLineEditQPushButton 小部件。 PySide 突出显示第一个 QLineEdit 和第一个 QPushButton.

如何让它一次专注于一件事?

我希望能够切换到 QPushButton。所以,关闭焦点不是我想要的,因为这使我无法进入按钮。

这是问题的图片:

代码如下:

#!/usr/bin/env python2.7
# -*- coding: utf-8 -*-

from PySide.QtCore import *
from PySide.QtGui  import *


class UI(object):
    def setupUi(self, SessionInfo):
        SessionInfo.setWindowTitle("Session Info")
#       SessionInfo.resize(313, 159)
        self.sessionLabel = QLabel(SessionInfo)
        self.sessionLabel.setText("Session information:")
        self.sessionId = QLineEdit(SessionInfo)
        self.presetsLabel = QLabel(SessionInfo)
        self.presetsLabel.setText("Presets:")
        self.presetsButton = QPushButton(SessionInfo)
        self.presetsButton.setText("Choose presets file")
        self.saveButton = QPushButton(SessionInfo)
        self.saveButton.setText("Begin session")
        self.saveButton.setFocusPolicy(Qt.StrongFocus)
        spacerItem = QSpacerItem(40, 20,
                                 QSizePolicy.Expanding,
                                 QSizePolicy.Minimum)
        self.gridLayout = QGridLayout(SessionInfo)
        self.gridLayout.addWidget(self.sessionLabel,   0, 0, 1, 1)
        self.gridLayout.addWidget(self.sessionId,      0, 1, 1, 2)
        self.gridLayout.addWidget(self.presetsLabel,   1, 0, 1, 1)
        self.gridLayout.addWidget(self.presetsButton,  1, 1, 1, 2)
        self.gridLayout.addItem(spacerItem,            2, 0, 1, 2)
        self.gridLayout.addWidget(self.saveButton,     2, 2, 1, 1)


def main():
    import sys
    app = QApplication(sys.argv)
    Dialog = QDialog()
    sessionInfo = UI()
    sessionInfo.setupUi(Dialog)
    Dialog.show()
    sys.exit(app.exec_())


if __name__ == "__main__":
    main()

您似乎不能为此使用 QDialog,因为它总是希望只有一个默认按钮,即使从一开始就是如此。 QWidget 反而更好,但在获得焦点时不会设置其按钮的默认值 属性。但是,您可以自己覆盖自定义按钮中的 focusInEventfocusOutEvent

示例:

from PySide.QtGui import *

class FocusButton(QPushButton):

    def __init__(self, *args, **kwargs):
        QPushButton.__init__(self, *args, **kwargs)

    def focusInEvent(self, event):
        self.setDefault(True)
        QPushButton.focusInEvent(self, event)

    def focusOutEvent(self, event):
        self.setDefault(False)
        QPushButton.focusOutEvent(self, event)

app = QApplication([])

dlg = QWidget()

label1 = QLabel("Label one")
label2 = QLabel("Label two")

edit1 = QLineEdit(dlg)

button1 = FocusButton("Button one")
button2 = FocusButton("Button two")

spacerItem = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)

gridLayout = QGridLayout(dlg)
gridLayout.addWidget(label1, 0, 0, 1, 1)
gridLayout.addWidget(edit1, 0, 1, 1, 2)
gridLayout.addWidget(label2, 1, 0, 1, 1)
gridLayout.addWidget(button1, 1, 1, 1, 2)
gridLayout.addItem(spacerItem, 2, 0, 1, 2)
gridLayout.addWidget(button2, 2, 2, 1, 1)

dlg.show()
app.exec_()

并且按钮最初不会突出显示,只有当它们获得焦点时。