Related
I am creating an oven monitoring program, that reaches out to some PID controllers over Modbus TCP. I am trying to implement an email alerting part that will monitor the temperature and if it's within tolerance. If it goes out of tolerance it is to send an email and then send another every 10 mins after that it stays out of tolerance. I am sure that I have something screwed up in my scope, but for the life of me I cannot figure out what. When the oven goes out of tolerance my 'inTolerance' function goes to work. It sends 1 email and should start the timer, but my 'is_alive' call does not return true. So when 'inTolerance' calls again it send another email and then bombs out as I believe it attempts to start another 't' timer.
Any help and a sanity check would be extremely helpful and appreciated.
from PyQt5 import QtCore, QtGui, QtWidgets
from modbusTest import Oven
from emailModule import emailer
import time
from threading import Timer
class Ui_Form(object):
def setupUi(self, Form):
Form.setObjectName("Form")
Form.resize(170, 260)
self.spinBox = QtWidgets.QSpinBox(Form)
self.spinBox.setGeometry(QtCore.QRect(10, 90, 61, 20))
self.spinBox.setObjectName("setpoint")
self.lcdNumber = QtWidgets.QLCDNumber(Form)
self.lcdNumber.setGeometry(QtCore.QRect(10, 10, 150, 60))
self.lcdNumber.setObjectName("lcdNumber")
self.pushButton = QtWidgets.QPushButton(Form)
self.pushButton.setGeometry(QtCore.QRect(120, 89, 41, 22))
self.pushButton.setObjectName("pushButton")
self.lineEdit = QtWidgets.QLineEdit(Form)
self.lineEdit.setGeometry(QtCore.QRect(10, 130, 105, 20))
font = QtGui.QFont()
font.setPointSize(8)
self.lineEdit.setFont(font)
self.lineEdit.setObjectName("lineEdit")
self.spinBox_2 = QtWidgets.QSpinBox(Form)
self.spinBox_2.setGeometry(QtCore.QRect(77, 90, 35, 20))
self.spinBox_2.setObjectName("tolerance")
self.spinBox_2.setValue(5)
self.label = QtWidgets.QLabel(Form)
self.label.setGeometry(QtCore.QRect(20, 70, 41, 15))
self.label.setObjectName("label")
self.label_2 = QtWidgets.QLabel(Form)
self.label_2.setGeometry(QtCore.QRect(10, 112, 71, 16))
self.label_2.setObjectName("label_2")
self.listWidget = QtWidgets.QListWidget(Form)
self.listWidget.setGeometry(QtCore.QRect(10, 160, 150, 91))
self.listWidget.setObjectName("listWidget")
self.label_3 = QtWidgets.QLabel(Form)
self.label_3.setGeometry(QtCore.QRect(70, 70, 51, 16))
self.label_3.setObjectName("label_3")
self.pushButton_2 = QtWidgets.QPushButton(Form)
self.pushButton_2.setGeometry(QtCore.QRect(120, 129, 40, 22))
self.pushButton_2.setObjectName("pushButton_2")
self.retranslateUi(Form)
QtCore.QMetaObject.connectSlotsByName(Form)
self.p1 = Oven('IP')
self.p1.connect()
self.lcdNumber.display(self.p1.readTemp())
#print(self.t.is_alive())
#self.t.start()
#print(self.t.is_alive())
#TODO set spinbox values to database table values
########################################################################################################
self.tolerance = float(self.spinBox_2.value())
self.spinBox.setValue(self.p1.readSP())
self.setPoint = float(self.spinBox.value())
########################################################################################################
self.pushButton.clicked.connect(self.setter)
QtCore.QTimer.singleShot(1000, self.displayer)
self.pushButton_2.clicked.connect(self.emailerList)
self.emailList = []
self.t = Timer(10.0, None)
def emailerList(self):
if len(self.lineEdit.text()) == 0:
None
else:
self.emailList.append(self.lineEdit.text())
self.listWidget.addItem(self.lineEdit.text())
self.lineEdit.clear()
def displayer(self):
temp = self.p1.readTemp()
self.lcdNumber.display(temp)
self.inTolerance(self.tolerance, temp, self.setPoint)
QtCore.QTimer.singleShot(1000, self.displayer)
def setter(self):
self.setPoint = float(self.spinBox.value())
self.p1.writeSP(self.setPoint)
self.tolerance = float(self.spinBox_2.value())
def inTolerance(self, tolerance, temp, setPoint):
if temp > (setPoint + tolerance) or temp < (setPoint - tolerance):
self.lcdNumber.setStyleSheet("background-color: rgb(255, 0, 0);")
print(self.t.is_alive())
if not self.t.is_alive():
emailer(self.emailList, 'Test Oven', temp, setPoint)
print('Email Sent')
self.t.start()
time.sleep(1)
print(self.t.is_alive())
else:
self.t.cancel()
self.lcdNumber.setStyleSheet("background-color: rgb(255, 255, 255);")
def retranslateUi(self, Form):
_translate = QtCore.QCoreApplication.translate
Form.setWindowTitle(_translate("Form", "Form"))
self.pushButton.setText(_translate("Form", "Set"))
self.label.setText(_translate("Form", "Setpoint"))
self.label_2.setText(_translate("Form", "Alarm Emails:"))
self.label_3.setText(_translate("Form", "Tolerance"))
self.pushButton_2.setText(_translate("Form", "Add"))
if __name__ == "__main__":
import sys
sys_argv = sys.argv
sys_argv += ['--style', 'Fusion']
app = QtWidgets.QApplication(sys_argv)
Form = QtWidgets.QWidget()
ui = Ui_Form()
ui.setupUi(Form)
Form.show()
sys.exit(app.exec_())
The main reason of your issue is that you're calling cancel(), which causes the timer to invalidate itself even if it has not been started yet, and the result is that after this the timer will be never actually started.
After that there is another problem: Thread objects can only be started once, and you would need to create a new Timer object whenever you want to start it again.
That said, you should not mix timer objects, and when dealing with threads it's usually better to use what Qt provides.
In your case, the solution is to use a QElapsedTimer, which is an object that can return the elapsed time since it was (re)started.
Note that I'm using a QWidget class (and simplified the ui just for this example), more about that after the code.
class Window(QtWidgets.QWidget):
def __init__(self, parent=None):
super(Window, self).__init__(parent)
self.resize(170, 260)
layout = QtWidgets.QGridLayout(self)
self.lcdNumber = QtWidgets.QLCDNumber(self)
layout.addWidget(self.lcdNumber, 0, 0, 1, 2)
self.spinBox = QtWidgets.QSpinBox(self)
layout.addWidget(self.spinBox, 1, 0)
self.spinBox_2 = QtWidgets.QSpinBox(self)
layout.addWidget(self.spinBox_2, 1, 1)
self.spinBox_2.setValue(5)
self.p1 = Oven('P1')
self.p1.connect()
self.lcdNumber.display(self.p1.readTemp())
self.tolerance = float(self.spinBox_2.value())
self.setPoint = float(self.spinBox.value())
self.emailList = []
# create a timer that will call displayer each second; having a reference
# to the timer allows to stop it if required
self.displayerTimer = QtCore.QTimer(interval=1000, timeout=self.displayer)
self.displayerTimer.start()
self.elapsedTimer = QtCore.QElapsedTimer()
def displayer(self):
temp = self.p1.readTemp()
self.lcdNumber.display(temp)
self.inTolerance(self.tolerance, temp, self.setPoint)
def inTolerance(self, tolerance, temp, setPoint):
if temp > (setPoint + tolerance) or temp < (setPoint - tolerance):
self.lcdNumber.setStyleSheet("background-color: rgb(255, 0, 0);")
if not self.elapsedTimer.isValid():
# the timer has not been started or has been invalidated
self.elapsedTimer.start()
elif self.elapsedTimer.elapsed() > 10000:
# ten seconds have passed, send the email
emailer(self.emailList, 'Test Oven', temp, setPoint)
# restart the timer, otherwise another mail could possibly be
# sent again the next cycle
self.elapsedTimer.start()
# in any other case, the elapsed time is less than the limit, just
# go on
else:
# temperature is within tolerance, invalidate the timer so that it can
# be restarted when necessary
self.elapsedTimer.invalidate()
self.lcdNumber.setStyleSheet("background-color: rgb(255, 255, 255);")
if __name__ == "__main__":
import sys
sys_argv = sys.argv
sys_argv += ['--style', 'Fusion']
app = QtWidgets.QApplication(sys_argv)
window = Window()
window.show()
sys.exit(app.exec_())
As said, I'm using a QWidget class.
It seems like you're using the output of the pyuic utility to create your program, which is something you should never do. You should create your program in a separate script, and use that generated file as an imported module. The py file created from pyuic should NEVER be edited.
In this case I created the interface completely from the code, but you can still recreate your ui in designer and use the generated py file as explained in the documentation (the third method, multiple inheritance approach, is usually the best).
So, Recently I was trying to make an audio player using PyQt5, pygame, and mutagen. The program works pretty fine. But when I'm playing a song and try to quit the program, the program stops responding and the song continues to play. But this doesn't happen when a song is not playing, it works fine then.
Here is the Code:
from PyQt5 import QtWidgets, QtGui
from PyQt5.QtWidgets import QApplication, QMainWindow, QSlider
from PyQt5.QtGui import QColor
from PyQt5.QtCore import Qt
import sys
import pygame as pg
from mutagen.mp3 import MP3
import os
import threading
pg.init()
#33206
class window(QMainWindow):
def __init__(self):
super(window, self).__init__()
self.setGeometry(425, 65, 400, 190)
self.setWindowIcon(QtGui.QIcon("icon"))
self.setWindowTitle("MultiMedia Player")
# MenuBar
file = QtWidgets.QAction("&Open Mp3", self)
file.setShortcut("Ctrl + O")
file.triggered.connect(self.open_mp3)
# Quit
quit = QtWidgets.QAction("&Quit", self)
quit.setShortcut("Q")
quit.triggered.connect(self.close_app)
# Add Items
items = QtWidgets.QAction("&Add Items", self)
items.setShortcut("Ctrl + P")
mainmenu = self.menuBar()
filemenu = mainmenu.addMenu("&Open")
filemenu.addAction(file)
add_items = mainmenu.addMenu("&Add Items")
add_items.addAction(items)
filemenu.addAction(quit)
self.flag = 0
self.home()
def home(self):
# colors
black = (13, 13, 13)
light_black = (36, 36, 36)
# Pause Button
self.pause_btn = QtWidgets.QPushButton(self)
self.pause_btn.setText("Pause")
self.pause_btn.setShortcut("p")
self.pause_btn.move(0, 120)
self.pause_btn.clicked.connect(self.pause)
# Play Button
self.play_btn = QtWidgets.QPushButton(self)
self.play_btn.setText("Play")
self.play_btn.setShortcut("Space")
self.play_btn.move(150, 120)
self.play_btn.clicked.connect(self.play)
# Stop Button
self.stop_btn = QtWidgets.QPushButton(self)
self.stop_btn.setText("Stop")
self.stop_btn.setShortcut("s")
self.stop_btn.move(300, 120)
self.stop_btn.clicked.connect(self.stop)
# color for the window
color = QColor(70, 70, 70)
# Volume_Up Button
self.vup_btn = QtWidgets.QPushButton(self)
self.vup_btn.setText("V(+)")
self.vup_btn.setShortcut("+")
self.vup_btn.move(300, 160)
self.vup_btn.clicked.connect(self.volume_up)
# Volume_Down Button
self.vdown_btn = QtWidgets.QPushButton(self)
self.vdown_btn.setText("V(-)")
self.vdown_btn.setShortcut("-")
self.vdown_btn.move(0, 160)
self.vdown_btn.clicked.connect(self.volume_down)
# Seek Slider
self.slider = QSlider(Qt.Horizontal, self)
self.slider.setGeometry(20, 75, 350, 20)
# Volume Slider
self.v_slider = QSlider(Qt.Horizontal, self)
self.v_slider.setGeometry(120, 165, 160, 20)
self.v_slider.setMinimum(0)
self.v_slider.setMaximum(100)
self.v_slider.setValue(70)
self.volume_value = self.v_slider.value()
self.v_slider.valueChanged.connect(self.slider_value_changed)
print(self.v_slider.value() / 100)
def msg(self, title, message):
msg1 = QtWidgets.QMessageBox()
msg1.setWindowIcon(QtGui.QIcon("icon"))
msg1.setWindowTitle(title)
msg1.setText(message)
msg1.setStandardButtons(QtWidgets.QMessageBox.Ok)
msg1.exec_()
def open_mp3(self):
name = QtWidgets.QFileDialog.getOpenFileName(self)
format = os.path.splitext(name[0])
if format[1] == ".mp3":
self.audio = MP3(name[0])
self.duration = self.audio.info.length//1
self.min = int(self.duration // 60)
self.sec = int(self.duration % 60)
self.total_time = str(self.min) + ":" + str(self.sec)
print(self.total_time)
self.slider.setMaximum(self.duration)
self.slider.setMinimum(0)
time = []
time.append(self.total_time)
self.label = QtWidgets.QLabel(self)
self.label.setText(self.total_time)
self.label.setFont(QtGui.QFont("Arial", 9))
self.label.adjustSize()
self.label.move(373, 77)
song = name[0]
pg.mixer.music.load(song)
pg.mixer.music.play(1)
pg.mixer.music.set_volume(self.v_slider.value()/100)
self.label = QtWidgets.QLabel(self)
self.label.setText(song)
self.label.setFont(QtGui.QFont("Arial", 15))
self.label.adjustSize()
self.label.move(0, 36)
self.label.show()
threading_1 = threading.Thread(target=self.cur_time).start()
else:
self.msg("Invalid Format", "Choose A .Mp3 File Only!")
volume_level = pg.mixer.music.get_volume()
print(volume_level)
def cur_time(self):
true = 1
while true == 1:
if self.flag == 0:
self.m_time = pg.mixer.music.get_pos()
self.mm_time = self.m_time * 0.001
self.s_time = self.mm_time // 1
self.slider.setValue(self.s_time)
print(self.s_time)
self.slider.sliderMoved.connect(self.seek_changed)
if self.s_time == -1:
self.slider.setValue(0)
true = 2
if self.flag == 1:
print(self.s_time)
def seek_changed(self):
print(self.slider.value())
pg.mixer.music.set_pos(self.slider.value())
def slider_value_changed(self):
self.volume_value = self.v_slider.value()
pg.mixer.music.set_volume(self.v_slider.value()/100)
def volume_up(self):
self.volume_value = self.volume_value + 10
self.v_slider.setValue(self.volume_value)
if self.volume_value >= 100:
self.volume_value = 100
pg.mixer.music.set_volume(self.v_slider.value() / 100)
print(self.v_slider.value() / 100)
def volume_down(self):
self.volume_value = self.volume_value - 10
self.v_slider.setValue(self.volume_value)
if self.volume_value <= 0:
self.volume_value = 0
pg.mixer.music.set_volume(self.v_slider.value() / 100)
print(self.v_slider.value() / 100)
def pause(self):
pg.mixer.music.pause()
self.flag = 1
def stop(self):
pg.mixer.music.stop()
self.flag = -1
def play(self):
pg.mixer.music.unpause()
self.flag = 0
def close_app(self):
choice = QtWidgets.QMessageBox.question(
self, "QUIT", "You Sure You Wanna Quit?", QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No)
if choice == QtWidgets.QMessageBox.Yes:
sys.exit()
else:
pass
def items(self):
layout = QtWidgets.QVBoxLayout(self)
song_name = QtWidgets.QFileDialog.getOpenFileName(self)
widget = QtWidgets.QListWidget()
widget.setAlternatingRowColors(True)
widget.setDragDropMode(
QtWidgets.QAbstractItemView.InternalMove)
widget.addItems([str(i) for i in range(1, 6)])
layout.addWidget(widget)
if __name__ == '__main__':
app = QApplication(sys.argv)
win = window()
win.show()
sys.exit(app.exec_())
Thanks In Advance.
The main problem is that you're still having the threading.Thread running, so while the QtApplication is "closed", the program is still alive.
You should really avoid using a while loop to check for the current position, as it will call request that value each time the loop cycles, consuming a lot of unnecessary CPU resources.
Also, you're connecting the sliderMoved signal to seek_changed each time the loops cycles, which is bad.
Use a QTimer instead, which will update the cursor position without overloading the process:
# create a timer in the window __init__
self.cursor_updater = QtCore.QTimer(interval=100, timeout=self.cur_time)
#...
def cur_time(self):
# ignore the update if the user is seeking
if self.slider.isSliderDown():
return
self.slider.setValue(pg.mixer.music.get_pos() * .001)
Then you just need to start the timer everytime the music starts (or unpauses) and stop whenever you stop or pause.
That said, there are other issues with your code.
pygame and Qt run their own event loops, so you can't easily and gracefully quit via sys.exit(), nor their own quit() functions, as it's possible that one or both of them would just hang in their own loop without being able to actually quit, keeping the process running (looping doing almost nothing) and consuming a lot of resources. I'm no expert in using pygame and PyQt but, as far as I know, you can call os._exit(0) instead.
the window closeEvent() should be taken care of, because if the user just closes the window without quitting, there won't be any confirmation dialog and the exit procedure described above won't be called.
pygame.mixer.music.get_pos() "only represents how long the music has been playing; it does not take into account any starting position offsets". So you'll need to keep track of the position whenever you use set_pos() and compute the actual value accordingly.
you should really consider using layouts, or ensure that the window size is fixed, otherwise the user will be able to resize it to a size smaller than the interface is.
I have seen some information posted about this, but everything seems to be with PyQt4 not PyQt5 and I'm not sure if there is a difference. I couldn't get anything to work.
What I want to do is have the program update a QLabel after the user inputs text into it and saves it. Right now I have the main window, with either a button or a selection from a drop down menu that will pop up a window with the ability to change setpoints.
Now what happens is the user can put in new data, but the code seems to still run and not wait for the user to make a change in the popup. calling my updateSetpoints function before anything changes.
# popups the reactorSetpoints window to change the setpoints for
# the reactor. This is where I am haiving troubles, the code
# continues before the user can input new setpoints
def reactorSetpoints(self):
exPopup = setpointsPopup(self)
self.updateSetpoints()
# just have it update the one value for now
def updateSetpoints(self):
self.pHUpperValue.setText(str(upper_pH))
A button calls reactorSetpoints(self) and popups a new window
import sys
import matplotlib.pyplot as plt
import random
from PyQt5.QtWidgets import QMainWindow, QAction, qApp, QApplication,QLineEdit, QPushButton, QWidget, QDialog, QTextEdit, QLabel, QMenu, QVBoxLayout, QSizePolicy
from PyQt5.QtGui import *
from PyQt5.QtCore import Qt, QTime, QTimer, QRect
from PyQt5 import QtCore
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
debug = True
setPointsChanged = False
versionNumber = 'V0.0.1'
currentState = 'Treatment'
currentCycTime = '2:15:42'
remaningCycTime = '5:44:18'
current_pH = 6.85
current_DO = 1.90
currentTemp = 24.9
lower_pH = 6.95
upper_pH = 7.20
lower_DO = 2.00
def openFile():
if debug == True:
print("Open File")
def saveFile():
if debug == True:
print("Save File")
def saveFileAs():
if debug == True:
print("Save File As...")
def editSysParm():
if debug == True:
print("Edit system parameters")
def reactorParameters():
if debug == True:
print("Edit reactor parameters")
def pHCalibration():
if debug == True:
print("pH Calibration")
def dOCalibration():
if debug == True:
print("DO calibration")
def pumpCalibration():
if debug == True:
print("Pump calibrations")
def editpHSetpoints():
pass
# sets up the setpoints popup window with either the option to save
# new setpoints, or to quit
class setpointsPopup(QDialog):
def __init__(self, parent = None):
super().__init__(parent)
self.initUI()
def initUI(self):
self.setGeometry(100,100,300,300)
self.upH = QLabel('Upper pH: ',self)
self.lpH = QLabel('Lower pH: ',self)
self.lDO = QLabel('Lower DO: ',self)
self.upHE = QLineEdit(self)
self.lpHE = QLineEdit(self)
self.lDOE = QLineEdit(self)
self.upHE.setPlaceholderText(str(upper_pH))
self.lpHE.setPlaceholderText(str(lower_pH))
self.lDOE.setPlaceholderText(str(lower_DO))
self.exitSetpoints = QPushButton('Exit', self)
self.saveSetpoints = QPushButton('Save New Setpoints', self)
self.upH.move(5,5)
self.upHE.move(90,5)
self.lpH.move(5,40)
self.lpHE.move(90,40)
self.lDO.move(5,75)
self.lDOE.move(90,75)
self.exitSetpoints.setGeometry(QRect(5,120,50,30))
self.exitSetpoints.clicked.connect(self.destroy)
self.saveSetpoints.setGeometry(QRect(60,120,150,30))
self.saveSetpoints.clicked.connect(self.verifySetpoints)
self.show()
#verification will be put here to make sure the input is valid
#but for now it will accept anything for ease of testing
def verifySetpoints(self):
global upper_pH
newUpH = self.upHE.text()
upper_pH = float(newUpH)
print(newUpH)
# Main window
class drawMenuBar(QMainWindow):
def __init__(self):
super().__init__()
self.topL = 20
self.top = 40
self.width = 1000
self.height = 500
self.title = ('Batch Reactor Controller ' + versionNumber)
self.initUI()
def initUI(self):
self.setWindowTitle(self.title)
self.setGeometry(self.topL, self.top, self.width, self.height)
exitAct = QAction('&Exit' , self)
exitAct.setShortcut('Ctrl+Q')
exitAct.setStatusTip('Exit Application')
exitAct.triggered.connect(qApp.quit)
openAct = QAction('&Open', self)
openAct.setShortcut('Ctrl+O')
openAct.setStatusTip('Open File')
openAct.triggered.connect(openFile)
saveAsAct = QAction('&Save As..', self)
saveAsAct.setShortcut('Shift+Ctrl+S')
saveAsAct.setStatusTip('Save as new file')
saveAsAct.triggered.connect(saveFileAs)
saveAct = QAction('Save', self)
saveAct.setStatusTip('Save')
saveAct.setShortcut('Ctrl+S')
saveAct.triggered.connect(saveFile)
systemSetpointsAct = QAction('Preferences', self)
systemSetpointsAct.setStatusTip('Edit system parameters')
systemSetpointsAct.triggered.connect(editSysParm)
reactorSetpointsAct = QAction('Reactor Setpoints', self)
reactorSetpointsAct.setStatusTip('Edit reactor setpoints')
reactorSetpointsAct.triggered.connect(self.reactorSetpoints)
reactorParametersAct = QAction('Reactor Parameters', self)
reactorParametersAct.setStatusTip('Edit batch reactor profiles')
reactorParametersAct.triggered.connect(reactorParameters)
pHCalibrationAct = QAction('pH Calibration', self)
pHCalibrationAct.setStatusTip('pH Calibration')
pHCalibrationAct.triggered.connect(pHCalibration)
dOCalibrationAct = QAction('DO Calibration', self)
dOCalibrationAct.setStatusTip('Dissolved oxygen calibration')
dOCalibrationAct.triggered.connect(dOCalibration)
pumpCalibrationAct = QAction('Pump Calibrations', self)
pumpCalibrationAct.setStatusTip('Pump Calibrations')
pumpCalibrationAct.triggered.connect(pumpCalibration)
menubar = self.menuBar()
self.statusBar()
fileMenu = menubar.addMenu('&File')
editMenu = menubar.addMenu('&Edit')
calibrationMenu = menubar.addMenu('&Calibration')
fileMenu.addAction(openAct)
fileMenu.addAction(saveAct)
fileMenu.addAction(saveAsAct)
fileMenu.addAction(exitAct)
calibrationMenu.addAction(pHCalibrationAct)
calibrationMenu.addAction(dOCalibrationAct)
calibrationMenu.addAction(pumpCalibrationAct)
editMenu.addAction(systemSetpointsAct)
editMenu.addAction(reactorSetpointsAct)
self.reactorTitle = QLabel('<b><u>Reactor 1 Status</u></b>', self)
font = self.reactorTitle.font()
font.setPointSize(20)
self.reactorTitle.setFont(font)
self.reactorTitle.setGeometry(QtCore.QRect(10,30, 250, 45)) #(x, y, width, height)
#pH Label
self.pHLabel = QLabel('<span style="color:blue"><b>pH:</b></span>',self)
font = self.pHLabel.font()
font.setPointSize(22)
self.pHLabel.setFont(font)
self.pHLabel.setGeometry(QtCore.QRect(10,50,100,100))
#displays current pH value
self.currentpH = QLabel('<b>' + str(current_pH) + '</b>', self)
font = self.currentpH.font()
font.setPointSize(22)
self.currentpH.setFont(font)
self.currentpH.setGeometry(QtCore.QRect(60,50,100,100))
#display lowerpH Setpoint
self.pHLowerLabel = QLabel('Lower pH setpoint: ', self)
font = self.pHLowerLabel.font()
font.setPointSize(10)
self.pHLowerLabel.setFont(font)
self.pHLowerLabel.setGeometry(QtCore.QRect(10, 105, 115, 50))
self.pHLowerValue = QLabel('{0:0.2f}'.format(lower_pH), self)
font = self.pHLowerValue.font()
font.setPointSize(10)
self.pHLowerValue.setFont(font)
self.pHLowerValue.setGeometry(QtCore.QRect(120, 105, 50, 50))
#display upper pH setpoint
self.pHUpperLabel = QLabel('Upper pH setpoint: ', self)
font = self.pHUpperLabel.font()
font.setPointSize(10)
self.pHUpperLabel.setFont(font)
self.pHUpperLabel.setGeometry(QtCore.QRect(10, 120, 115, 50))
self.pHUpperValue = QLabel('{0:0.2f}'.format(upper_pH), self)
font = self.pHUpperValue.font()
font.setPointSize(10)
self.pHUpperValue.setFont(font)
self.pHUpperValue.setGeometry(QtCore.QRect(120, 120, 50, 50))
#pH button options
self.pHToGraph = QPushButton('Graph pH', self)
self.pHToGraph.move(10,160)
self.pHToGraph.setToolTip('Show pH in live graph')
self.pHToGraph.clicked.connect(self.displaypHGraph)
self.pHSetpointsButton = QPushButton('Update Setpoints', self)
self.pHSetpointsButton.setGeometry(QtCore.QRect(115, 160, 150, 30))
self.pHSetpointsButton.setToolTip('Edit pH Setpoints')
self.pHSetpointsButton.clicked.connect(self.reactorSetpoints)
self.DOLabel = QLabel('<span style="color:blue"><b>DO:</b></span>',self)
font = self.DOLabel.font()
font.setPointSize(22)
self.DOLabel.setFont(font)
self.DOLabel.setGeometry(QtCore.QRect(10,175,100,100))
self.currentDO = QLabel('<b>' + str(current_DO) + ' mg/L</b>', self)
font = self.currentDO.font()
font.setPointSize(22)
self.currentDO.setFont(font)
self.currentDO.setGeometry(QtCore.QRect(60,175,150,100))
self.DOLowerLabel = QLabel('Lower DO setpoint: ', self)
font = self.DOLowerLabel.font()
font.setPointSize(10)
self.DOLowerLabel.setFont(font)
self.DOLowerLabel.setGeometry(QtCore.QRect(10, 225, 115, 50))
self.DOLowerValue = QLabel('{0:0.2f}'.format(lower_DO) + ' mg/L', self)
font = self.DOLowerValue.font()
font.setPointSize(10)
self.DOLowerValue.setFont(font)
self.DOLowerValue.setGeometry(QtCore.QRect(120, 225, 75, 50))
self.DOToGraph = QPushButton('Graph DO', self)
self.DOToGraph.move(10,260)
self.DOToGraph.setToolTip('Show DO in live graph')
self.DOToGraph.clicked.connect(self.displaypHGraph)
self.tempLabel = QLabel('<span style="color:blue"><b>Temperature:</b></span>',self)
font = self.tempLabel.font()
font.setPointSize(22)
self.tempLabel.setFont(font)
self.tempLabel.setGeometry(QtCore.QRect(10,265,190,100))
self.currentTemp = QLabel('<b>' + str(currentTemp) + '\u2103', self)
font = self.currentTemp.font()
font.setPointSize(22)
self.currentTemp.setFont(font)
self.currentTemp.setGeometry(QtCore.QRect(195,265,150,100))
self.currentStatus = QLabel('<b><u>Other Parameters</u><b>', self)
font = self.currentStatus.font()
font.setPointSize(10)
self.currentStatus.setFont(font)
self.currentStatus.setGeometry(QtCore.QRect(10, 325, 200, 50))
self.currentStatus = QLabel('Current Cycle: ' + '<b>' + currentState + '</b>', self)
font = self.currentStatus.font()
font.setPointSize(10)
self.currentStatus.setFont(font)
self.currentStatus.setGeometry(QtCore.QRect(10, 340, 200, 50))
self.currentCycleTime = QLabel('Current Cycle Time (HH:MM:SS): ' + '<b>' + currentCycTime + '</b>', self)
font = self.currentCycleTime.font()
font.setPointSize(10)
self.currentCycleTime.setFont(font)
self.currentCycleTime.setGeometry(QtCore.QRect(10, 355, 250, 50))
self.remaningCycleTime = QLabel('Remaning Cycle Time (HH:MM:SS): ' + '<b>' + remaningCycTime + '</b>', self)
font = self.remaningCycleTime.font()
font.setPointSize(10)
self.remaningCycleTime.setFont(font)
self.remaningCycleTime.setGeometry(QtCore.QRect(10, 370, 275, 50))
self.show()
# just a dummy graph that I got off a tutorial, it works for what
# i need it to do for now
def displaypHGraph(self):
print("Display pH")
self.m = LinePlot(self, width = 16, height = 9)
self.m.setGeometry(QtCore.QRect(300,40,660,370))
self.m.show()
def displayDOGraph(self):
pass
# was playing with how to update labels here. Just a counter
# that counts up the value from the initial
# this will eventually be replaced with sensor inputs
def updatepH(self):
global current_pH
global lower_pH
global upper_pH
current_pH = current_pH + 0.01
display_pH = '{0:0.2f}'.format(current_pH)
if current_pH < lower_pH:
self.currentpH.setText('<span style="color:red"><b>' + str(display_pH) + '</b></span>')
elif current_pH > upper_pH:
self.currentpH.setText('<span style="color:red"><b>' + str(display_pH) + '</b></span>')
else:
self.currentpH.setText('<span style="color:black"><b>' + str(display_pH) + '<b></span>')
# same thing as with the updatepH function except for DO
def updateDO(self):
global current_DO
global lower_DO
current_DO = current_DO + 0.01
display_DO = '{0:0.2f}'.format(current_DO)
if current_DO < lower_DO:
self.currentDO.setText('<span style = "color:red"><b>' + str(display_DO) + ' mg/L</b></span>')
else:
self.currentDO.setText('<span style = "color:black"><b>' + str(display_DO)+ ' mg/L</b></span>')
# popups the reactorSetpoints window to change the setpoints for
# the reactor. This is where I am haiving troubles, the code
# continues before the user can input new setpoints
def reactorSetpoints(self):
exPopup = setpointsPopup(self)
self.updateSetpoints()
# just have it update the one value for now
def updateSetpoints(self):
self.pHUpperValue.setText(str(upper_pH))
# dummy plot, was learning how to put a matplotlib
# it works for now
class LinePlot(FigureCanvas):
def __init__(self, parent=None, width=16, height=9, dpi=100):
fig = Figure(figsize=(width, height), dpi=dpi)
self.axes = fig.add_subplot(111)
FigureCanvas.__init__(self, fig)
self.setParent(parent)
FigureCanvas.setSizePolicy(self, QSizePolicy.Expanding,QSizePolicy.Expanding)
FigureCanvas.updateGeometry(self)
self.plot()
def plot(self):
data = [6.89,6.90,6.91,6.92,6.93,6.92,6.96,6.99,7.12,7.14,6.98,6.93,7.01,6.90,7.11,7.21,7.13,6.99]
ax = self.figure.add_subplot(111)
ax.plot(data, 'r-')
ax.set_title('pH')
ax.set_xlabel('Time')
ax.set_ylabel('pH Value')
self.draw()
def main():
app = QApplication(sys.argv)
ex = drawMenuBar()
timer = QTimer()
timer.timeout.connect(ex.updatepH)
timer.timeout.connect(ex.updateDO)
timer.start(1000)
ex.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
so all of this works, except the only way I can get the label to update is to close out of the setpoints popup and reopen it. What is a good way to update it upon exiting of the popup window?
Thanks.
I have a piece of code that is running, communication between two threads and status. I have faced with problem how to update QLineEdit field based on emitted value. So far, it works fine with commented lines, but it's not what I am looking for... How to modify show_process function to do the job...some help will be more than welcome?
import sys, time
from PyQt4 import QtGui, QtCore
class Window(QtGui.QMainWindow):
def __init__(self):
super(Window, self).__init__()
self.setGeometry(50, 50, 500, 200)
self.setWindowTitle("TEST APP!")
self.home()
def Label(self, name, width, length, fontSize) :
label_name = QtGui.QLabel(name, self)
label_name.move(width,length)
label_font = label_name.font()
label_font.setPointSize(fontSize)
label_name.setFont(label_font)
def Field(self, TrueFalse, width, length, startText) :
field_name = QtGui.QLineEdit(self)
field_name.setDisabled(TrueFalse)
field_name.move(width, length)
field_name.setAlignment(QtCore.Qt.AlignCenter)
field_name.setText(startText)
def home(self):
self.Label('TEST1', 10, 60, 10)
self.Label('TEST2', 10, 120, 10)
self.Field(True, 130, 60, 'Ready') # first one
self.Field(True, 130, 120, 'Ready') # second one
self.start = QtGui.QPushButton("start", self)
self.start.clicked.connect(self.startPressed)
self.start.move(260, 20)
self.stop = QtGui.QPushButton("Stop", self)
self.stop.clicked.connect(self.stopPressed)
self.stop.move(380, 20)
self.show()
def startPressed(self):
self.get_thread_start = Start_Process('239.200.10.1', 50010)
self.stop.clicked.connect(self.get_thread_start.terminate)
self.start.setDisabled(True)
self.get_thread_start.updated.connect(self.show_process)
self.get_thread_start.start()
def stopPressed(self):
self.start.setDisabled(False)
self.get_thread_start.running = False
def show_process(self, data):
if str(data) == '1' :
#self.textbox1.setText(str(data))
pass
elif str(data) == '0' :
#self.textbox2.setText(str(data))
pass
class Start_Process(QtCore.QThread):
updated = QtCore.pyqtSignal(int)
running = True
def __init__(self, mcstaddr, mcstport):
QtCore.QThread.__init__(self)
self.counter = 0
self.array = [1,0,1,0,1,0,1,0,1]
def run(self):
while self.running:
for i in self.array :
self.updated.emit(i)
time.sleep(0.5)
def main():
app = QtGui.QApplication(sys.argv)
GUI = Window()
GUI.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
A simple way to access the widget is to create a container, in this case we choose a dictionary:
self.field_dict = {}
Then we add in the Field() method we add the QLineEdits to the dictionary.
def Field(self, TrueFalse, width, length, startText, key) :
field_name = QtGui.QLineEdit(self)
...
self.field_dict[key] = field_name
Then we can get the QLineEdit through the key.
def show_process(self, key, data):
self.field_dict[key].setText(data)
Complete Example:
import sys, time
from PyQt4 import QtGui, QtCore
class Window(QtGui.QMainWindow):
def __init__(self):
super(Window, self).__init__()
self.setGeometry(50, 50, 500, 200)
self.setWindowTitle("TEST APP!")
self.field_dict = {}
self.home()
def Label(self, name, width, length, fontSize) :
label_name = QtGui.QLabel(name, self)
label_name.move(width,length)
label_font = label_name.font()
label_font.setPointSize(fontSize)
label_name.setFont(label_font)
def Field(self, TrueFalse, width, length, startText, key) :
field_name = QtGui.QLineEdit(self)
field_name.setDisabled(TrueFalse)
field_name.move(width, length)
field_name.setAlignment(QtCore.Qt.AlignCenter)
field_name.setText(startText)
self.field_dict[key] = field_name
def home(self):
self.Label('TEST1', 10, 60, 10)
self.Label('TEST2', 10, 120, 10)
self.Field(True, 130, 60, 'Ready', 0) # first one
self.Field(True, 130, 120, 'Ready', 1) # second one
self.start = QtGui.QPushButton("start", self)
self.start.clicked.connect(self.startPressed)
self.start.move(260, 20)
self.stop = QtGui.QPushButton("Stop", self)
self.stop.clicked.connect(self.stopPressed)
self.stop.move(380, 20)
self.show()
def startPressed(self):
self.get_thread_start = Start_Process('239.200.10.1', 50010)
self.stop.clicked.connect(self.get_thread_start.terminate)
self.start.setDisabled(True)
self.get_thread_start.updated.connect(self.show_process)
self.get_thread_start.start()
def stopPressed(self):
self.start.setDisabled(False)
self.get_thread_start.running = False
def show_process(self, key, data):
self.field_dict[key].setText(data)
class Start_Process(QtCore.QThread):
updated = QtCore.pyqtSignal(int, str)
running = True
def __init__(self, mcstaddr, mcstport):
QtCore.QThread.__init__(self)
self.counter = 0
self.array = [1,0,1,0,1,0,1,0,1]
def run(self):
while self.running:
for i in self.array :
self.updated.emit(i, str(self.counter))
time.sleep(0.5)
self.counter += 1
def main():
app = QtGui.QApplication(sys.argv)
GUI = Window()
GUI.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
I am trying to create a window that receives simple event notifications from a Process. Here is the code that I have so far:
import wx, wx.lib.newevent, time, sys
from multiprocessing import Process
size_width = 320
size_height = 240
background_color = (226,223,206)
SomeNewEvent, EVT_SOME_NEW_EVENT = wx.lib.newevent.NewEvent()
class StatusWindow(wx.Frame):
def __init__(self, parent):
super(StatusWindow, self).__init__(parent, title='Monitor', size=(size_width, size_height))
self.Bind(EVT_SOME_NEW_EVENT, self.updateStatus)
staticBox = wx.StaticBox(self, label='Monitor Status:', pos=(5, 105), size=(size_width - 28, size_height/3))
self.statusLabel = wx.StaticText(staticBox, label='None', pos=(10, 35), size=(size_width, 20), style=wx.ALIGN_LEFT)
self.count = 0
self.InitUI()
self.monitor = cMonitor()
self.monitor.start()
def InitUI(self):
panel = wx.Panel(self)
self.SetBackgroundColour(background_color)
self.Centre()
self.Show()
def updateStatus(self, evt):
self.statusLabel.SetLabel(evt.attr1)
class cMonitor(Process):
def __init__(self):
super(cMonitor, self).__init__()
def run(self):
time.sleep(2)
print 'This is an update'
#create the event
evt = SomeNewEvent(attr1="Some event has just occured")
#post the event
wx.PostEvent(EVT_SOME_NEW_EVENT, evt)
if __name__ == '__main__':
app = wx.App()
window = StatusWindow(None)
app.MainLoop()
The window gets created, but the Process does not appear to be either executing or sending the post event notification correctly. I should note that the print statement in the run method is not showing up either. What is causing the GUI to not be updated?? This was what I used as a reference:
http://wiki.wxpython.org/CustomEventClasses
First of all, your code throws an error:
Traceback (most recent call last):
File "C:\Python27\lib\multiprocessing\process.py", line 232, in _bootstrap
self.run()
File "C:\PyProgs\stackoverflow_answers\wx_answers\wx_events1.py", line 44, in run
wx.PostEvent(EVT_SOME_NEW_EVENT, evt)
File "C:\Python27\lib\site-packages\wx-3.0-msw\wx\_core.py", line 8410, in PostEvent
return _core_.PostEvent(*args, **kwargs)
TypeError: in method 'PostEvent', expected argument 1 of type 'wxEvtHandler *'
According the docs, PostEvent(dest, event) send an event to a window or other wx.EvtHandler to be processed later, but in your code first parameter has type PyEventBinder. Your code would have to look something like this:
wx.PostEvent(self.wxWindow, evt)
where self.wxWindow - object of StatusWindow class. But there is another problem: you can not use wxPython objects as multiprocessor arguments(link).
One way to do what you want - using threading module instead multiprocessing:
import wx, wx.lib.newevent, time, sys
from threading import *
size_width = 320
size_height = 240
background_color = (226,223,206)
SomeNewEvent, EVT_SOME_NEW_EVENT = wx.lib.newevent.NewEvent()
class StatusWindow(wx.Frame):
def __init__(self, parent):
super(StatusWindow, self).__init__(parent, title='Monitor', size=(size_width, size_height))
self.Bind(EVT_SOME_NEW_EVENT, self.updateStatus)
staticBox = wx.StaticBox(self, label='Monitor Status:', pos=(5, 105), size=(size_width - 28, size_height/3))
self.statusLabel = wx.StaticText(staticBox, label='None', pos=(10, 35), size=(size_width, 20), style=wx.ALIGN_LEFT)
self.count = 0
self.InitUI()
# Set up event handler for any worker thread results
self.monitor = cMonitor(self)
self.monitor.start()
def InitUI(self):
panel = wx.Panel(self)
self.SetBackgroundColour(background_color)
self.Centre()
self.Show()
def updateStatus(self, evt):
self.statusLabel.SetLabel(evt.attr1)
class cMonitor(Thread):
def __init__(self, wxWindow):
super(cMonitor, self).__init__()
self.wxWindow = wxWindow
def run(self):
time.sleep(2)
print 'This is an update'
#create the event
evt = SomeNewEvent(attr1="Some event has just occured")
#post the event
wx.PostEvent(self.wxWindow, evt)
if __name__ == '__main__':
app = wx.App()
window = StatusWindow(None)
app.MainLoop()