2

假设我有一个包含许多 QGroupBoxes 的应用程序,如下所示:

import sys


from PyQt4 import QtGui, QtCore


class Main(QtGui.QWidget):
    # pylint: disable=too-many-statements
    def __init__(self, main):
        super(Main, self).__init__()
        self.grid_layout = QtGui.QGridLayout()

        self.line_edit = QtGui.QLineEdit()
        self.grid_layout.addWidget(self.create_settings_group(), 0, 0, 2, 1)

        self.push_button = QtGui.QPushButton("go", self)
        self.grid_layout.addWidget(self.create_controls_group(), 0, 1)

        self.setLayout(self.grid_layout)
        main.setCentralWidget(self)

    def create_settings_group(self):
        group_box_settings = QtGui.QGroupBox(self)
        group_box_settings.setTitle("group1")
        grid = QtGui.QGridLayout()
        grid.addWidget(self.line_edit, 0, 0)
        group_box_settings.setLayout(grid)
        return group_box_settings

    def create_controls_group(self):
        group_box_settings = QtGui.QGroupBox(self)
        group_box_settings.setTitle("group2")
        grid = QtGui.QGridLayout()
        grid.addWidget(self.push_button, 0, 0, 1, 2)
        group_box_settings.setLayout(grid)
        return group_box_settings


class GUI(QtGui.QMainWindow):

    def __init__(self):
        super(GUI, self).__init__()
        self.ui = Main(self)
        self.show()


app = QtGui.QApplication(sys.argv)
ex = GUI()
app.exec_()

当我打开我的简单应用程序时,我看到光标在行编辑中闪烁。但我只想突出显示另一个组框中的按钮并连接到它?我怎么做?使用 self.push_button.setFocus() 不会做任何事情。

4

2 回答 2

4

您必须在出现后立即设置焦点,您可以使用 aQTimer::singleShot()QMetaObject::invokeMethod()

1.QTimer::singleShot()

...
self.push_button = QtGui.QPushButton("go", self)
self.grid_layout.addWidget(self.create_controls_group(), 0, 1)

self.push_button.setDefault(True)
QtCore.QTimer.singleShot(0, self.push_button.setFocus)

2.QMetaObject::invokeMethod()

...
self.push_button = QtGui.QPushButton("go", self)
self.grid_layout.addWidget(self.create_controls_group(), 0, 1)

self.push_button.setDefault(True)
QtCore.QMetaObject.invokeMethod(self.push_button, 
    "setFocus",
    QtCore.Qt.QueuedConnection)
于 2018-10-17T15:50:58.787 回答
3

您可以尝试设置按钮Default属性:

self.push_button.setDefault(True)
self.push_button.setFocus()
于 2018-10-17T11:57:19.093 回答