我正在尝试学习使用PySide2,对于该应用程序,我正在开发中,我需要一个弹出对话框来显示Qlabel和Ok按钮。确定按钮应被禁用或隐藏,直到在show()之后调用该函数为止。我当前的问题是,直到从同一实例调用的函数完成,Qlabel和Ok按钮才可见。
一些示例代码为:
from PySide2.QtWidgets import *
import time
import sys
def main():
app = QApplication(sys.argv)
dialog_home = HomeScreen()
dialog_home.show()
app.exec_()
class HomeScreen(QDialog):
def __init__(self):
QDialog.__init__(self)
layout = QVBoxLayout()
self.setWindowTitle("Example problem")
test_label = QLabel("text that should be visible")
test_button = QPushButton("test")
layout.addWidget(test_label)
layout.addWidget(test_button)
self.setLayout(layout)
self.setFocus()
test_button.clicked.connect(self.open_window)
def open_window(self):
self.close()
self.new_window = Window()
self.new_window.show()
self.new_window.test_function()
class Window(QDialog):
def __init__(self):
QDialog.__init__(self)
layout = QVBoxLayout()
self.setWindowTitle("test window")
ok_button = QPushButton("Ok")
status_label = QLabel("here the text should become visible directly but waits till function finished")
layout.addWidget(status_label)
layout.addWidget(ok_button)
self.setLayout(layout)
self.setFocus()
ok_button.clicked.connect(self.show_home_screen)
def show_home_screen(self):
self.dialog_home = HomeScreen()
self.dialog_home.show()
self.close()
def test_function(self):
time.sleep(5)
main()
我希望一旦show()被调用,Qlabel和按钮就会出现。这样,我就可以从同一实例调用的函数中操作Qlabel的文本,并且可以在此窗口中使用户保持最新状态。
但是,该窗口完全是空的,直到self.new_window.test_function()完成。只有这样,它才会显示按钮和标签,而不是根据需要立即显示。
编辑:我以time.sleep为例。在我的真实代码中,我正在使用调用的功能重新启动Windows服务。这将导致相同的行为,其中按钮和标签仅在功能完成后才会显示。在调用函数之前先调用show()。
我目前无法使用PC访问互联网。但基本上,我调用win32serviceutil.RestartService(service)并检查重新启动是否已在真实函数中成功完成。
编辑2:在本指南的帮助下,我设法解决了问题:https://pythonguis.com/courses/multithreading-pyqt-applications-qthreadpool/background-preparation/如果您遇到相同类别的内容,请检查该帖子,完全值得阅读!