如何处理QT QWidget启动中的信号和事件后立即运行代码?

问题描述 投票:0回答:1
import sys
from PyQt5.Qt import *

app = QApplication([])


class MyDialog(QDialog):
    def __init__(self):
        super().__init__()
        layout = QVBoxLayout(self)
        self.list_widget = QListWidget()
        layout.addWidget(self.list_widget)
        self.list_widget.currentRowChanged.connect(self.on_cur_row_changed)
        self.list_widget.addItems(['apple', 'orange'])

        # code block A # start #
        self.clear_qt_currentRow()
        # code block A # end   #

        print('End of MyDialog.__init__')

    def on_cur_row_changed(self, row):
        print('Current row changed to: ', row)

    def clear_qt_currentRow(self):
        print('Clear Qt currentRow')
        self.list_widget.selectionModel().clear()


dialog = MyDialog()
dialog.show()
sys.exit(app.exec())

正如上面的代码,我不喜欢QT将列表小部件的currentRow属性设置为0(第一行)。我想在QT中的信号和事件之后,在clear_qt_currentRow()中运行代码QWidget初始化已处理(在这种情况下,将currentRow属性设置为None)但是代码块A中的self.clear_qt_currentRow()运行得太早了(在QT更改currentRow之前)。结果显示为:

Clear Qt currentRow
End of MyDialog.__init__
Current row changed to:  0

然后,我在代码块A的下面尝试了两种替代方法,但仍然无法使self.clear_qt_currentRow()足够晚地运行。

# alternative 1
app.processEvents()
self.clear_qt_currentRow()

# result:
# Clear Qt currentRow
# End of MyDialog.__init__
# Current row changed to:  0
# alternative 2
QTimer.singleShot(0, self.clear_qt_currentRow)

# result:
# End of MyDialog.__init__
# Clear Qt currentRow
# Current row changed to:  0

我知道QTimer.singleShot(10000,self.clear_qt_currentRow)可以做到。但这不是一个“真实”的解决方案,因为用户可能拥有规格不同的计算机。

对我有什么建议吗?

编辑:在粗体字中添加我想做的事情。

编辑:在@ zariiii9003的帮助下,我更改为下面的代码,该代码在类中起作用。

import sys
from PyQt5.Qt import *

app = QApplication([])


class MyDialog(QDialog):
    def __init__(self):
        super().__init__()
        layout = QVBoxLayout(self)
        self.list_widget = QListWidget()
        layout.addWidget(self.list_widget)
        self.list_widget.currentRowChanged.connect(self.on_cur_row_changed)
        self.list_widget.addItems(['apple', 'orange'])
        # code block A # start #
        QTimer.singleShot(0, self.clear_qt_currentRow)
        # code block A # end   #
        print('End of MyDialog.__init__')

    def on_cur_row_changed(self, row):
        print('Current row changed to: ', row)

    def clear_qt_currentRow(self):
        print('Process events')
        # add here
        app.processEvents()
        print('Clear Qt currentRow')
        self.list_widget.selectionModel().clear()


dialog = MyDialog()
dialog.show()
sys.exit(app.exec())

python pyqt pyqt5 qt-signals
1个回答
1
投票

您可以看一下使用Qt实现的IDE Spyder:

© www.soinside.com 2019 - 2024. All rights reserved.