i want to make a program that count pulses then it go through some equation and display it in the gui .
This my main.py
import sys
import time
import RPi.GPIO as GPIO
import PyQt5
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from mainwindow import Ui_MainWindow
GPIO.setmode(GPIO.BCM)
GPIO.setup(18, GPIO.IN, pull_up_down = GPIO.PUD_UP)
class MainWindow(QMainWindow):
# access variables inside of the UI's file
def __init__(self):
super().__init__()
self.mainwindow = Ui_MainWindow()
self.mainwindow.setupUi(self)
self.i=100
self.flow = 0
self.flowliter = 0
self.totalflow=0
self.mainwindow.lcdNumber.display(self.i)
self.mainwindow.lcdNumber_2.display(self.i)
self.show()
self.mainwindow.startbttn.clicked.connect(lambda: self.pressedstartButton())
self.mainwindow.stopbttn.clicked.connect(lambda: self.pressedstopButton())
def pressedstartButton(self):
print ("Pressed On!")
self.data()
def pressedstopButton(self):
print ("Pressed Off!")
def data(self) :
global count
count = 0
def countPulse(channel):
global count
if start_counter == 1:
count = count+1
GPIO.add_event_detect(FLOW_SENSOR, GPIO.FALLING, callback=countPulse)
while True:
try:
start_counter = 1
time.sleep(1)
start_counter = 4
self.flow = (10 * 60)
self.flowliter= (self.flow/60)
self.totalflow += self.flowliter
print("%d"% (count))
print ("The flow is: %.3f Liter/min" % (self.flow))
print ("The flowliter is: %.3f Liter" % (self.flowliter))
print ("The volume is: %.3f Liter" % (self.totalflow))
self.mainwindow.lcdNumber.display(self.flow)
self.mainwindow.lcdNumber_2.display(self.flowliter)
count = 0
time.sleep(1)
except KeyboardInterrupt:
print ('\ncaught keyboard interrupt!, bye')
GPIO.cleanup()
sys.exit()
def main():
app = QApplication(sys.argv)
form = MainWindow()
form.show()
sys.exit(app.exec_())
if __name__ == "__main__":
main()
the lcdnumber doesnt update in the gui but the self.flow update in the shell and i want display the value
in the gui but i dont know which one suitable qtablewidget or qtextbroswer
this code should count the pulse from the gpio 18 and show the flow in the gui.
You should not use time-consuming functions as they block the eventloop and the consequence is to freeze the GUI. In this case, you should not use an infinite loop or time.sleep but a QTimer is enough.
import sys
import RPi.GPIO as GPIO
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from mainwindow import Ui_MainWindow
FLOW_SENSOR = 18
class MainWindow(QMainWindow):
pinSignal = pyqtSignal()
def __init__(self):
super().__init__()
self.mainwindow = Ui_MainWindow()
self.mainwindow.setupUi(self)
self.i = 100
self.flow = 0
self.flowliter = 0
self.totalflow = 0
self.mainwindow.lcdNumber.display(self.i)
self.mainwindow.lcdNumber_2.display(self.i)
self.show()
self.mainwindow.startbttn.clicked.connect(self.pressedstartButton)
self.mainwindow.stopbttn.clicked.connect(self.pressedstopButton)
self.start_counter = False
self.count = 0
self.timer = QTimer(self, interval=1000, timeout=self.execute_every_second)
self.pinSignal.connect(self.handle_pin_signal)
def pressedstartButton(self):
print("Pressed On!")
GPIO.add_event_detect(FLOW_SENSOR, GPIO.FALLING, callback = lambda *args: self.pinSignal.emit())
self.execute_every_second()
self.timer.start()
def pressedstopButton(self):
print("Pressed Off!")
self.timer.stop()
GPIO.remove_event_detect(FLOW_SENSOR)
def handle_pin_signal(self):
if self.start_counter:
self.count += 1
def execute_every_second(self):
if not self.start_counter:
self.flow = 10 * 60
self.flowliter = self.flow / 60
self.totalflow += self.flowliter
print("%d" % (self.count))
print("The flow is: %.3f Liter/min" % (self.flow))
print("The flowliter is: %.3f Liter" % (self.flowliter))
print("The volume is: %.3f Liter" % (self.totalflow))
self.mainwindow.lcdNumber.display(self.flow)
self.mainwindow.lcdNumber_2.display(self.flowliter)
self.count = 0
self.start_counter = not self.start_counter
def main():
GPIO.setmode(GPIO.BCM)
GPIO.setup(FLOW_SENSOR, GPIO.IN, pull_up_down=GPIO.PUD_UP)
app = QApplication(sys.argv)
form = MainWindow()
form.show()
ret = app.exec_()
GPIO.cleanup()
sys.exit(ret)
if __name__ == "__main__":
main()
Related
I have a project to build GUI for raspberry project thermocycler. I have some error in pushbutton GUI. I can start the thermocycler from pushbutton GUI, but can't to stop. When thermocycler is on, my GUI freeze. I will write my code below. If anyone have a solution for my error please. what is need use a threading?
my code
import sys
from PySide2 import *
from PySide2.QtGui import QPainter
from PySide2.QtWidgets import (QMainWindow, QApplication)
from PySide2.QtCharts import QtCharts
from PySide2.QtGui import QPainter
from PySide2.QtWidgets import (QMainWindow, QApplication)
from PySide2.QtCharts import QtCharts
from random import randrange
from functools import partial
import csv
import time
import math
import RPi.GPIO as GPIO
import Adafruit_ADS1x15
from datetime import datetime
file_date = datetime.now().strftime('%Y-%m-%d-%H-%M-%S')
from ui_interface4 import 4
shadow_elements = {
"left_menu_frame",
"frame_3",
"frame_5",
"header_frame",
"frame_9"
}
temp_denat = 95
temp_anel = 55
temp_exten = 72
temp_refri = 4
heat_pin = 19 #pwm > GPIO 19 > LPWM
cool_pin = 18 #pwm > GPIO 13 > RPWM
pwm_fan = 12 #pwm > GPIO 12 > fan cooling
low_volt = 21 #digital > GPIO 21 > 3v3
class MainWindow(QMainWindow):
def __init__(self, parent=None):
QMainWindow.__init__(self)
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
self.setWindowFlags(QtCore.Qt.FramelessWindowHint)
self.setAttribute(QtCore.Qt.WA_TranslucentBackground)
self.shadow = QGraphicsDropShadowEffect(self)
self.shadow.setBlurRadius(20)
self.shadow.setXOffset(0)
self.shadow.setYOffset(0)
self.ui.centralwidget.setGraphicsEffect(self.shadow)
self.setWindowIcon(QtGui.QIcon(":/icons/icons/pie-chart.svg"))
self.setWindowTitle("PCR_2")
QSizeGrip(self.ui.size_grip)
self.ui.minimize_window_button.clicked.connect(lambda: self.showMinimized())
self.ui.close_window_button.clicked.connect(lambda: self.close())
self.ui.restore_window_button.clicked.connect(lambda: self.restore_or_maximize_window())
switch = False
def Program_Run (switch):
def suhu_c(R, Ro=100000.0, To=25.0, beta=3950.0):
suhu = math.log(R / Ro)
suhu /= beta
suhu += 1.0 / (To + 273.15)
suhu = (1.0 / suhu)
suhu -=273.15
return suhu
GPIO.setwarnings(False) #disable warning
GPIO.setmode(GPIO.BCM) #board GPIO
GPIO.setup(heat_pin,GPIO.OUT)
GPIO.setup(cool_pin,GPIO.OUT)
GPIO.setup(pwm_fan,GPIO.OUT)
GPIO.setup(low_volt,GPIO.OUT)
GPIO.output(low_volt,GPIO.HIGH)
adc = Adafruit_ADS1x15.ADS1115(address=0x49,busnum=1)
GAIN = 2/3
t = 0
rn = 100000
pwm_val = 0
print('channel-0 value')
told = time.time()
cool = GPIO.PWM(heat_pin,490) #490Hz
heat = GPIO.PWM(cool_pin,490) #490Hz
fan = GPIO.PWM(pwm_fan,490) #490Hz
heat.start(0)
cool.start(0)
fan.start(0)
while switch == True:
range = time.time() - told
bit = adc.read_adc_difference(0,gain=GAIN)
voltage = (bit*6.144)/32768
R = rn*((5*rn)-(voltage*2*rn))/((5*rn)+(voltage*2*rn))
suhu = suhu_c(R)
if suhu <= temp_denat:
pwm = 96
cool.ChangeDutyCycle(0)
heat.ChangeDutyCycle(pwm)
fan.ChangeDutyCycle(0)
if suhu >= temp_denat:
pwm = 80
cool.ChangeDutyCycle(pwm)
heat.ChangeDutyCycle(0)
fan.ChangeDutyCycle(100)
if range >= 1.00:
print(t,' ADC bit:',round(bit),' bit', ',voltage: ',round(voltage,3),' volt','suhu', round(suhu,3), ' C','R:',round(R,3),'ohm')
t += 1
told = time.time()
while switch == False:
break
def Start_Program():
switch = True
Program_Run (switch)
def Stop_Program():
switch = False
Program_Run (switch)
def moveWindow(e):
if self.isMaximized() == False: #Not maximized
if e.buttons() == Qt.LeftButton:
self.move(self.pos() + e.globalPos() - self.clickPosition)
self.clickPosition = e.globalPos()
e.accept()
self.ui.header_frame.mouseMoveEvent = moveWindow
self.show()
for x in shadow_elements:
## # Shadow effect style
effect = QtWidgets.QGraphicsDropShadowEffect(self)
effect.setBlurRadius(18)
effect.setXOffset(0)
effect.setYOffset(0)
effect.setColor(QColor(0, 0, 0, 255))
getattr(self.ui, x).setGraphicsEffect(effect)
self.ui.START_btn.clicked.connect(Start_Program)
self.ui.CANCEL_btn.clicked.connect(Stop_Program)
def restore_or_maximize_window(self):
if self.isMaximized():
self.showNormal()
self.ui.restore_window_button.setIcon(QtGui.QIcon(u":/icons/icons/maximize-2.svg"))
else:
self.showMaximized()
self.ui.restore_window_button.setIcon(QtGui.QIcon(u":/icons/icons/minimize-2.svg"))
def mousePressEvent(self, event):
self.clickPosition = event.globalPos()
if __name__ == "__main__":
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
I wrote a simple script that pops up a window and starts a countdown timer. It looks like this:
When the timer reachers zero, it resets back to 7 seconds (or whatever I set in that variable). I'd like to start the app with a 30 seconds timer, have it count down to zero, reset to 10 seconds, then to 30 again and so on. The utlimate goal is to remind me to do something every 10 minutes or so, but only for a few seconds. So for example, the app will count down from 10 minutes, reach zero, remind me to stretch for 10 seconds, but when those 10 seconds are up, it will reset to 10 minutes again and so forth, until I close the app.
Here is the code I've got so far:
from PyQt5 import QtWidgets
from PyQt5.QtWidgets import QApplication, QMainWindow
from PyQt5 import QtCore
import sys
import time
from win10toast import ToastNotifier
DURATION_INT = 7
toaster = ToastNotifier()
def secs_to_minsec(secs: int):
mins = secs // 60
secs = secs % 60
minsec = f'{mins:02}:{secs:02}'
return minsec
class App(QtWidgets.QMainWindow):
def __init__(self):
super().__init__()
self.time_left_int = DURATION_INT
self.myTimer = QtCore.QTimer(self)
# App window
self.app = QApplication(sys.argv)
self.win = QMainWindow()
self.win.setGeometry(200, 200, 200, 200)
self.win.setWindowTitle("test")
# Widgets
self.titleLabel = QtWidgets.QLabel(self.win)
self.titleLabel.setText("Welcome to my app")
self.titleLabel.move(50,20)
self.timerLabel = QtWidgets.QLabel(self.win)
self.timerLabel.move(50,50)
self.timerLabel.setAlignment(QtCore.Qt.AlignCenter)
self.timerLabel.setStyleSheet("font: 10pt Helvetica")
self.startButton = QtWidgets.QPushButton(self.win)
self.startButton.setText("Start")
self.startButton.move(50,100)
self.startButton.clicked.connect(self.startTimer)
self.stopButton = QtWidgets.QPushButton(self.win)
self.stopButton.setText("Minimize")
self.stopButton.move(50,130)
self.update_gui()
# Show window
self.win.show()
sys.exit(app.exec_())
def startTimer(self):
self.time_left_int = DURATION_INT
self.myTimer.timeout.connect(self.timerTimeout)
self.myTimer.start(1000)
def timerTimeout(self):
self.time_left_int -= 1
if self.time_left_int == 0:
self.time_left_int = DURATION_INT
self.update_gui()
def update_gui(self):
minsec = secs_to_minsec(self.time_left_int)
self.timerLabel.setText(minsec)
# def minimize():
# pass
app = QtWidgets.QApplication(sys.argv)
main_window = App()
main_window.show()
sys.exit(app.exec_())
I'm not so sure how to logically do what I'm trying to do, any help would be appreciated.
Use itertools.cycle to cycle between a series of values indefinitely, then just call next() on it inside your timeout code. Each call gets the next value in the cycle:
import itertools
TIME_CYCLER = itertools.cycle([30, 10]) # 30 seconds, 10 seconds
# your other code here
def startTimer(self):
self.time_left_int = next(TIME_CYCLER)
self.myTimer.timeout.connect(self.timerTimeout)
self.myTimer.start(1000)
def timerTimeout(self):
self.time_left_int -= 1
if self.time_left_int == 0:
self.time_left_int = next(TIME_CYCLER)
I have a situation where a Gui is active and a QThread.
The QThread is getting and saving data in the background all the time, it should not stop doing this.
Now I want to process the latest data from the QThread without interrupting the QThread or freezing the Gui.
So I think I need another thread to do this?!
How can I pass its data to another thread and do something with it?
import sys, random, time
from PyQt5 import QtWidgets
from PyQt5.QtCore import *
class Ui(QtWidgets.QMainWindow):
def __init__(self):
super(Ui, self).__init__()
self.setWindowTitle('Window')
#getData
self.myGetData = getData()
self.myGetData.start()
self.show()
class getData(QThread):
#This Thread should run all the time
def run(self):
while True:
myNumber = random.randint(0, 100)
#He 'processData Thread'!! Do Something with mynumber!!
time.sleep(1)
class processData(QThread):
def processNumber(self, myNumber):
#Extremly complex code will execute while 'getData' is doing its thing.
newNumber = myNumber * 10
return newNumber
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
window = Ui()
sys.exit(app.exec_())
Found a lot of examples on how to pass data from a QThread to the interface (signals).. But not the other way around.
The signals are confusing me a bit in this case..
I would like to propose do next:
import sys, random, time
from PyQt5 import QtWidgets
from PyQt5.QtCore import *
from PyQt5 import Qt #+
class getData(QThread):
#This Thread should run all the time
threadSignalGetData = pyqtSignal(int)
def __init__(self, myNumber):
super().__init__()
self.myNumber = myNumber
def run(self):
#myNumber = 0
while True:
#He 'processData Thread'!! Do Something with mynumber!!
Qt.QThread.msleep(1000)
self.myNumber += 1
self.threadSignalGetData.emit(self.myNumber)
class MsgBoxGetData(Qt.QDialog):
def __init__(self):
super().__init__()
layout = Qt.QVBoxLayout(self)
self.label = Qt.QLabel("")
layout.addWidget(self.label)
close_btn = Qt.QPushButton("Close window GetData")
layout.addWidget(close_btn)
close_btn.clicked.connect(self.close)
self.setGeometry(900, 65, 400, 80)
self.setWindowTitle('MsgBox GetData')
self.setStyleSheet("""QLabel{
font-family:'Consolas';
color: green;
font-size: 16px;}""")
class processData(QThread):
threadSignalProcessData = pyqtSignal(int, int)
def __init__(self, myNumber):
super().__init__()
self.newNumber = myNumber
def run(self):
flagProcessData = True
while flagProcessData:
#Extremly complex code will execute while 'getData' is doing its thing.
newNumber = self.newNumber * 10
self.threadSignalProcessData.emit(self.newNumber, newNumber)
flagProcessData = False
class MsgBoxProcessData(Qt.QDialog):
def __init__(self):
super().__init__()
layout = Qt.QVBoxLayout(self)
self.label = Qt.QLabel("")
layout.addWidget(self.label)
close_btn = Qt.QPushButton("Close window ProcessData")
layout.addWidget(close_btn)
close_btn.clicked.connect(self.close)
self.setGeometry(900, 200, 400, 80)
self.setWindowTitle('MsgBox ProcessData')
self.setStyleSheet("""QLabel{
font-family:'Consolas';
color: red;
font-size: 24px;}""")
class Ui(Qt.QWidget):
def __init__(self, parent=None):
super(Ui, self).__init__(parent)
layout = Qt.QVBoxLayout(self)
self.lbl = Qt.QLabel("process GUI")
layout.addWidget(self.lbl)
self.btnA = Qt.QPushButton("Start getData")
layout.addWidget(self.btnA)
self.btnB = Qt.QPushButton("Start processData")
layout.addWidget(self.btnB)
self.setGeometry(550, 65, 300, 300)
self.setWindowTitle('Window')
self.btnA.clicked.connect(self.usingGetData)
self.btnB.clicked.connect(self.usingProcessData)
self.myNumber = 0
self.newNumber = None
self.msgGetData = MsgBoxGetData()
self.threadGetData = None
self.msgProcessData = MsgBoxProcessData()
self.threadProcessData = None
self.counter = 0
self.timer = Qt.QTimer()
self.timer.setInterval(1000)
# -------- timeout -------> def recurring_timer(self):
self.timer.timeout.connect(self.recurring_timer)
self.timer.start()
self.setStyleSheet("""QLabel{
font-family:'Consolas';
color: blue;
font-size: 20px;}""")
self.show()
def recurring_timer(self):
self.counter += 1
self.lbl.setText("process GUI: %d" % self.counter)
# ---- getData(QThread) -----------------------------------------------------#
def usingGetData(self):
if self.threadGetData is None:
self.threadGetData = getData(self.myNumber)
self.threadGetData.threadSignalGetData.connect(self.on_threadSignalGetData)
self.threadGetData.finished.connect(self.finishedGetData)
self.threadGetData.start()
self.btnA.setText("Stop getData(QThread)")
else:
self.threadGetData.terminate()
self.threadGetData = None
self.btnA.setText("Start getData(QThread)")
def finishedGetData(self):
self.threadGetData = None
self.btnA.setText("Start getData(QThread)")
def on_threadSignalGetData(self, value):
self.myNumber = value
self.msgGetData.label.setText(str(self.myNumber))
if not self.msgGetData.isVisible():
self.msgGetData.show()
# --END-- getData(QThread) -------------------#
# ---- processData(QThread) -----------------------------------------------------#
def usingProcessData(self):
if self.threadProcessData is None:
self.threadProcessData = processData(self.myNumber)
self.threadProcessData.threadSignalProcessData.connect(self.on_threadSignalProcessData)
self.threadProcessData.finished.connect(self.finishedProcessData)
self.threadProcessData.start()
self.btnB.setText("Stop processData(QThread)")
else:
self.threadProcessData.terminate()
self.threadProcessData = None
self.btnB.setText("Start processData(QThread)")
def finishedProcessData(self):
self.threadProcessData = None
self.btnB.setText("Start processData(QThread)")
def on_threadSignalProcessData(self, value1, value2):
self.newNumber = value2
self.msgProcessData.label.setText(str(value1)+" * 10 = "+str(self.newNumber))
if not self.msgProcessData.isVisible():
self.msgProcessData.show()
# --END-- processData(QThread) -------------------#
# -------------------- closeEvent --------------------------------------- #
def closeEvent(self, event):
reply = Qt.QMessageBox.question\
(self, 'Question',
"QUIT ?",
Qt.QMessageBox.Yes,
Qt.QMessageBox.No)
if reply == Qt.QMessageBox.Yes:
# close getData(QThread)
if self.threadGetData:
self.threadGetData.terminate()
self.msgGetData.close()
# close processData(QThread)
if self.threadProcessData:
self.threadProcessData.terminate()
self.msgProcessData.close()
#event.accept()
super().closeEvent(event)
else:
event.ignore()
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
window = Ui()
sys.exit(app.exec_())
So I'm trying to make a simple file downloader in Python 3.4.2 and PyQt5
QThreads seems to be the way but there's no tutorials online or examples that I could understand for PyQt5. All I could find was Qt5 Reference for C/C++ and bunch of PyQt4 tutorials that don't work for PyQt5 and Python 3
Here's the GUI screenshot: http://i.imgur.com/KGjqRRK.png
And here's my code:
#!usr/bin/env python3
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from string import Template
import urllib.request
import sys
class Form(QWidget):
def __init__(self, parent=None):
super(Form, self).__init__(parent)
lblUrl= QLabel("File URL:")
self.txtURL = QLineEdit()
self.bttDL = QPushButton("&Download")
self.pbar = QProgressBar()
self.pbar.setMinimum(0)
buttonLayout1 = QVBoxLayout()
buttonLayout1.addWidget(lblUrl)
buttonLayout1.addWidget(self.txtURL)
buttonLayout1.addWidget(self.bttDL)
buttonLayout1.addWidget(self.pbar)
self.bttDL.clicked.connect(self.bttPush)
mainLayout = QGridLayout()
mainLayout.addLayout(buttonLayout1, 0, 1)
self.setLayout(mainLayout)
self.setWindowTitle("pySFD")
def bttPush(self):
# check if the download is already running or just disable the button
# while it's running
url = self.txtURL.text()
if url == "":
QMessageBox.information(self, "Empty URL",
"Please enter the URL of the file you want to download.")
return
else:
filename = str(QFileDialog.getSaveFileName(self, 'Choose the download location and file name', '.'))
filename = filename[:-6]
filename = filename.split("('",maxsplit=1)[1]
self.dlThread = downloaderThread()
self.dlThread.connect(dlThread.run)
self.dlThread.start()
self.dlThread.emit(url)
class downloaderThread(QThread):
def __init__(self):
QThread.__init__(self)
def __del__(self):
self.wait()
def run(self, dlLink):
while dlLink.length == 0:
QThread.sleep(1)
pass
def report(block_count, block_size, total_size):
if block_count == 0:
self.pbar.setValue(0)
if (block_count * block_size) == total_size:
QMessageBox.information(self,"Done!","Download finished!")
return
self.pbar.setValue(self.pbar.value() + block_size)
urllib.request.urlretrieve(dlLink, filename, reporthook=report)
self.terminate()
if __name__ == '__main__':
app = QApplication(sys.argv)
screen = Form()
screen.show()
sys.exit(app.exec_())
I've tried a lot of ways and it just doesn't seem to work.
How do I make the progress bar (self.pbar) show the download progress in real time?
PS. This downloader is on my GitHub: https://github.com/dKatara/pySFD
Fixed it, it's not done yet, but threading works great!
Most recent version is on my GitHub here: https://github.com/dKatara/pySFD
#!usr/bin/env python3
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
import urllib.request
import sys
import threading
dlThread = 0
hWindow = 0
fProgressCounter = 0.0
class Form(QWidget):
def __init__(self, parent=None):
super(Form, self).__init__(parent)
global hWindow
hWindow = self
lblUrl = QLabel("File URL:")
self.txtURL = QLineEdit()
self.bttDL = QPushButton("&Download")
self.pbar = QProgressBar()
self.pbar.setMinimum(0)
self.pbar.setMaximum(100)
buttonLayout1 = QVBoxLayout()
buttonLayout1.addWidget(lblUrl)
buttonLayout1.addWidget(self.txtURL)
buttonLayout1.addWidget(self.bttDL)
buttonLayout1.addWidget(self.pbar)
self.bttDL.clicked.connect(self.bttPush)
mainLayout = QGridLayout()
mainLayout.addLayout(buttonLayout1, 0, 1)
self.setLayout(mainLayout)
self.setWindowTitle("pySFD")
def bttPush(self):
global dlThread
hSignals = sigHandling()
hSignals.dlProgress_update.connect(hSignals.pbar_incrementer)
hSignals.dlProgress_done.connect(hSignals.dlDone)
url = self.txtURL.text()
if url == "":
QMessageBox.information(self, "Empty URL",
"Please enter the URL of the file you want to download.")
return
else:
filename = str(QFileDialog.getSaveFileName(self, 'Choose the download location and file name', '.')) ## DETECT A CANCEL
filename = filename[:-6]
filename = filename.split("('",maxsplit=1)[1]
self.bttDL.setEnabled(False)
dlThread = threading.Thread(target=hSignals.runDL,args=(url, filename))
dlThread.start()
return
def pbarIncValue(self, val):
global fProgressCounter
#print("pbarIncValue({0})\nfProgressCounter={1}".format(val,fProgressCounter))
if self.pbar.value() >= 100:
self.dlProgress_done.emit()
return
if fProgressCounter > 1.0: # FIX
self.pbar.setValue(self.pbar.value() + 1)
fProgressCounter -= 1.0
fProgressCounter += val
else:
fProgressCounter += val
class sigHandling(QObject):
dlProgress_update = pyqtSignal(float)
dlProgress_done = pyqtSignal()
#pyqtSlot(float)
def pbar_incrementer(self, val):
hWindow.pbarIncValue(val)
#pyqtSlot()
def dlDone(self):
print("in dlDone")
hWindow.pbar.setValue(100)
hWindow.bttDL.setEnabled(True)
def runDL(self, dlLink, filename):
#print("in run")
global dlThread, hWindow
def report(block_count, block_size, total_size):
if block_count == 0:
#print("block_count == 0")
self.dlProgress_update.emit(0)
if (block_count * block_size) == total_size:
self.dlProgress_done.emit()
incAmount = float((100*block_size) / total_size)
#print("BS={0} TS={1} incAmount={2}".format(block_size,total_size,incAmount))
self.dlProgress_update.emit(incAmount)
urllib.request.urlretrieve(dlLink, filename, reporthook=report)
#print("emit dlProgress_done")
self.dlProgress_done.emit()
#print("about to leave dlThread")
pass
if __name__ == '__main__':
app = QApplication(sys.argv)
screen = Form()
screen.show()
sys.exit(app.exec_())
I'm trying to learn PyQt4 and has made the following Gui for this purpose - it has no other use.
The code works almost as expected - the only thing that doesn't is the 'else' clause.
import sys
import time
from PyQt4.QtCore import *
from PyQt4.QtGui import *
class Form(QDialog):
def __init__ (self, parent=None):
super(Form, self).__init__(parent)
self.startButton = QPushButton('Start')
self.stopButton = QPushButton('Stop')
self.browser = QTextBrowser()
self.myLabel = QLabel()
layout = QVBoxLayout()
layout.addWidget(self.startButton)
layout.addWidget(self.stopButton)
layout.addWidget(self.browser)
layout.addWidget(self.myLabel)
self.setLayout(layout)
self.startButton.setFocus()
self.startButton.clicked.connect(self.guiLoop)
self.stopButton.clicked.connect(self.guiLoop)
self.setWindowTitle('Loop Gui')
def guiLoop(self):
state = False
text = self.sender()
self.myLabel.setText(text.text())
time.sleep(1)
if text.text() == 'Start':
state = True
else:
state = False
i = 0
while state:
time.sleep(.1)
self.browser.append(str(i))
QApplication.processEvents()
i += 1
else:
self.browser.append('Stop loop')
time.sleep(3)
sys.exit()
app = QApplication(sys.argv)
form = Form()
form.show()
app.exec_()
...I'd expect that the program would print 'Stop loop' in the browser widget before exiting, but it doesn't
else:
self.browser.append('Stop loop')
time.sleep(3)
sys.exit()
I now have 3 questions:
Why doesn't it print 'Stop loop'
If you imagine that the loop was instead a data stream from a serial connection, how could I print only every 10th value. In the loop that would be 1, 11, 21 ... and so on
General comments on my code
Thx in advance
Add the following line in your else part
QApplication.processEvents()
like
while state:
time.sleep(.1)
if i % 10 == 1:
self.browser.append(str(i))
QApplication.processEvents()
i += 1
else:
self.browser.append('Stop loop')
QApplication.processEvents()
time.sleep(3)
sys.exit()
Output is like: 1 11 21 31 etc.. and Stop Loop