如何在PyQt5中创建循环和AutoClosed消息框
这是一种可以在3秒后自动关闭的消息框。
我想通过循环使用它来显示消息。
我该怎么做?
PS:代码不是我写的
import sys
from PyQt5 import QtCore, QtGui, QtWidgets, Qt
import time
class Ui_Message(object):
def setupUi(self, Form):
Form.setObjectName("Form")
Form.resize(538, 91)
self.frame = QtWidgets.QFrame(Form)
self.frame.setGeometry(QtCore.QRect(0, 0, 541, 111))
# self.frame.setStyleSheet("background-image: url(:/img/messageback.png);")
self.frame.setFrameShape(QtWidgets.QFrame.StyledPanel)
self.frame.setFrameShadow(QtWidgets.QFrame.Raised)
self.frame.setObjectName("frame")
self.label = QtWidgets.QLabel(self.frame)
self.label.setGeometry(QtCore.QRect(0, 0, 531, 91))
font = QtGui.QFont()
font.setPointSize(31)
font.setBold(False)
font.setWeight(50)
self.label.setFont(font)
self.label.setStyleSheet("background-color: transparent;n"
"fontsize: 30px;")
self.label.setAlignment(QtCore.Qt.AlignCenter)
self.label.setObjectName("label")
self.retranslateUi(Form)
QtCore.QMetaObject.connectSlotsByName(Form)
def retranslateUi(self, Form):
_translate = QtCore.QCoreApplication.translate
Form.setWindowTitle(_translate("Form", "Form"))
self.label.setText(_translate("Form", "显示信息"))
# import img_rc
# Define a removable borderless 3S prompt message interface
class MessageWindow(Qt.QMainWindow):
def __init__(self, parent=None):
Qt.QWidget.__init__(self, parent)
self.ui = Ui_Message()
self.ui.setupUi(self)
self.setWindowFlags(Qt.Qt.FramelessWindowHint)
QtCore.QTimer().singleShot(3000, self.close)
self.show()
def mousePressEvent(self, event):
# Define mouse click events
if event.button() == QtCore.Qt.LeftButton:
self.dragPosition = event.globalPos() - self.frameGeometry().topLeft()
event.accept()
def mouseMoveEvent(self, event):
# Define mouse movement events
if event.buttons() == QtCore.Qt.LeftButton:
self.move(event.globalPos() - self.dragPosition)
event.accept()
def setMessage(self, message):
self.ui.label.setText(message)
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
login = MessageWindow()
#----how can i maike a loop messagebox?------
for i in range(0,5):
login.setMessage("Number"+str(i))
time.sleep(3)
sys.exit(app.exec())
我知道也许我不能在PyQt5中使用time.sleep,但我已经搜索了任何东西,但没有得到答案。
在Qt中,如果要执行周期性任务,则必须使用QTimer,并且忘记同步逻辑,因为必须处理事件。
在这种情况下,一种可能的解决方案是使用存储信息的队列,并且在定时器的每个镜头中都获得一个元素。
from collections import deque
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
login = MessageWindow()
values = range(0, 5)
q = deque(values)
def on_timeout():
print(q)
if q:
i = q.popleft()
Qt.QTimer.singleShot(3000, on_timeout)
login.setMessage("Number" + str(i))
on_timeout()
sys.exit(app.exec())
注:
- 您的类不能从QMainWindow继承,而是从QWidget继承
- 您必须取消关闭窗口的计时器,否则您将不会看到文本更改,因为时间很短