python - 为什么我的 2 函数在第一个和第二个循环中没有被调用?
问题描述
我正在研究这个 pyqt5 UI 设计,我需要遍历 id 并检查 True/false 并相应地更新窗口。当我运行此代码并提供 3 个 id 时,它仅在最后一个 id 期间调用 getsensor 函数和 paintevent 函数。当 id 为 id_123 和 id_234 时,为什么在第 2 次循环期间没有调用函数 getsensor 和 paintevent。
from PyQt5.QtWidgets import QApplication, QMainWindow, QLabel
from PyQt5.QtCore import QTimer, Qt
import sys
from PyQt5.QtGui import QPainter, QBrush, QPen, QColor
import time
class MainWindow(QMainWindow):
def __init__(self,id_, parent=None):
super(MainWindow, self).__init__(parent)
# counter
self.correct = 0
self.incorrect = 0
self.id_ = id_
self.setStyleSheet("QLabel {font: 8pt Arial}")
self.qLbl = QLabel("Not yet initialized")
self.setCentralWidget(self.qLbl)
self.qTimer = QTimer()
self.qTimer.setInterval(1000)
self.qTimer.singleShot(1000, self.getSensorValue)
# self.qTimer.timeout.connect(self.getSensorValue)
self.qTimer.setSingleShot(True)
self.qTimer.start()
self.color = QColor()
self.repaint()
self.update()
def getSensorValue(self):
result = (bool(random.getrandbits(1)))
print("Result",self.id_,result)
if result == True:
self.correct = self.correct + 1
else:
self.incorrect = self.incorrect + 1
# self.qLbl.setText("{} {}".format(id_, result))
self.qLbl.setText(" {} {} {}".format(str(self.id_), self.correct, self.incorrect))
# self.color = QColor("green") if result==True else QColor("red")
if result == True:
self.color =QColor("green")
elif result == False:
self.color = QColor("red")
else:
self.color =QColor("black")
self.repaint()
self.update()
# return result
def paintEvent(self, event):
print("test1",self.id_)
if self.color.isValid():
painter = QPainter(self)
painter.setPen(QPen(self.color, 5, Qt.SolidLine))
painter.setBrush(QBrush(self.color, Qt.SolidPattern))
painter.drawRect(40, 40, 400, 200)
#
qApp = QApplication(sys.argv)
ids=["id_123","id_234","id_345"]
for i in ids:
import random
qWin = MainWindow(id_=i)
# qWin.getSensorValue()
time.sleep(1)
qWin.setGeometry(100, 100, 1000, 1000)
qWin.show()
sys.exit(qApp.exec_())
# run application
解决方案
它仅使用最后一个 id,因为您在循环外显示窗口
我建议研究 MVC 或 MVP 模式,其中您的数据与任何 GUI 分开存储
推荐阅读
- c - 访问 QSPI 读取时 QSPI 时钟的不可预测行为
- javascript - Iphone 预览其他日期然后 android 设备
- javascript - 如何从我的 web 地图中检索存储在 postgis 中并与 geoserver 一起提供的模型执行的结果层?
- artifactory - JFrog Artifactory 副本分布
- compact-framework - Sql Server Compact 中缺少文件
- cucumber - 更新黄瓜版本后线程“主”中的异常
- postgresql - 使用 PostgreSQL 选择随机点
- javascript - 使用 for 循环创建幻灯片效果时 setInterval 不起作用
- java - Java 8:将文件读入字符串
- windows - 如何使用 Dialogflow 在 Electron 中修复“net::ERR_NAME_NOT_RESOLVED”