使用组框设置应用程序中按钮的焦点

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


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() 不会做任何事情。


BIG阳
浏览 176回答 2
2回答

泛舟湖上清波郎朗

您必须在出现后立即设置焦点,您可以使用 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)

至尊宝的传说

您可以尝试设置按钮Default属性:self.push_button.setDefault(True)self.push_button.setFocus()
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python