如何在没有用户交互的情况下显示模态QDialog?

2024-10-03 21:36:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我想展示一个无框架的模态对话框,它不提供任何交互,甚至不能关闭对话框。其思想是打开对话框以显示警告正在进行的长操作的消息,运行该操作,然后关闭对话框。你知道吗

qt文档似乎表明可以在不执行事件循环的情况下显示模式对话框:https://doc.qt.io/qt-5/qdialog.html#modal-dialogs

但是当我这样做的时候,对话框永远不会在屏幕上正确呈现。我得到一个黑色的小部件,它的标签仍然是看不见的。你知道吗

这是我的尝试:

from PyQt5.QtGui import *
from PyQt5.QtWidgets import *


class ModalInfoDialog(QDialog):
    """
    Frameless modal dialog with no interaction
    """

    def __init__(self, text1="Loading project",
                 text2="", parent=None):
        super().__init__(parent)
        self.setWindowFlags(Qt.Window | Qt.FramelessWindowHint)
        self.setModal(True)
        self.setStyleSheet(
            """
            QDialog {
                background-color: white;
                border: none;
            }
            """)

        layout = QVBoxLayout(self)
        self.setLayout(layout)

        firstLine = QLabel(text1)
        secondLine = QLabel(text2)

        layout.addWidget(firstLine)
        layout.addWidget(secondLine)


import time
app = QApplication([])

d = ModalInfoDialog("haha!", "huh?")
d.show()
QApplication.processEvents()  # does not help
time.sleep(3)
d.close()

Tags: fromimportselfinitqtpyqt5parent对话框
1条回答
网友
1楼 · 发布于 2024-10-03 21:36:27

您不必使用processEvents,而是在另一个线程中实现任务,在本例中,我创建了一个QObject,它位于另一个线程中,并在任务结束时发出一个用于关闭窗口的信号。你知道吗

import time
from PyQt5 import QtCore, QtWidgets


class ModalInfoDialog(QtWidgets.QDialog):
    """
    Frameless modal dialog with no interaction
    """

    def __init__(self, text1="Loading project", text2="", parent=None):
        super().__init__(parent)
        self.setWindowFlags(QtCore.Qt.Window | QtCore.Qt.FramelessWindowHint)
        self.setModal(True)
        self.setStyleSheet(
            """
            QDialog {
                background-color: white;
                border: none;
            }
            """
        )

        layout = QtWidgets.QVBoxLayout(self)

        firstLine = QtWidgets.QLabel(text1)
        secondLine = QtWidgets.QLabel(text2)

        layout.addWidget(firstLine)
        layout.addWidget(secondLine)


class Worker(QtCore.QObject):
    finished = QtCore.pyqtSignal()

    @QtCore.pyqtSlot()
    def task(self):
        time.sleep(3)
        self.finished.emit()


if __name__ == "__main__":
    import sys

    app = QtWidgets.QApplication(sys.argv)
    d = ModalInfoDialog("haha!", "huh?")
    d.show()
    thread = QtCore.QThread(d)
    worker = Worker()
    worker.finished.connect(d.close)
    worker.moveToThread(thread)
    thread.started.connect(worker.task)
    thread.start()
    sys.exit(app.exec_())

相关问题 更多 >