I tried to use the mutex. Why did it automatically stop without an error - pyqt

I tried to use the mutex. Why did it automatically stop without an error.
Running will stop automatically after a while
This is my code, which can be run directly. Please help me to see what the problem is
Is my method wrong? Is there a better way to achieve it? I don't want my interface to get stuck
`
import time
from PyQt5 import QtWidgets, QtCore
from PyQt5.QtCore import QWaitCondition, QMutex
from PyQt5.QtWidgets import QMainWindow, QMessageBox, QApplication, QDesktopWidget
from PyQt5.QtCore import pyqtSignal
import sys
from PyQt5.QtCore import QThread
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(800, 600)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.horizontalLayout = QtWidgets.QHBoxLayout(self.centralwidget)
self.horizontalLayout.setObjectName("horizontalLayout")
self.pushButton = QtWidgets.QPushButton(self.centralwidget)
self.pushButton.setObjectName("pushButton")
self.horizontalLayout.addWidget(self.pushButton)
self.label = QtWidgets.QLabel(self.centralwidget)
self.label.setObjectName("label")
self.horizontalLayout.addWidget(self.label)
self.pushButton_2 = QtWidgets.QPushButton(self.centralwidget)
self.pushButton_2.setObjectName("pushButton_2")
self.horizontalLayout.addWidget(self.pushButton_2)
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 23))
self.menubar.setObjectName("menubar")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.pushButton.setText(_translate("MainWindow", "PushButton"))
self.label.setText(_translate("MainWindow", "TextLabel"))
self.pushButton_2.setText(_translate("MainWindow", "stop"))
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
self.__init2__()
def __init2__(self):
self.search_running = False
self.ui.pushButton.clicked.connect(self.search)
self.ui.pushButton_2.clicked.connect(self.stop_search)
def stop_search(self):
if self.search_running:
reply = QMessageBox.information(self, 'notice', 'Do you want to stop searching?',
QMessageBox.Yes | QMessageBox.Cancel)
if reply == QMessageBox.Yes:
self.search_thread.terminate()
self.__thread.resume()
self.search_running = False
self.ui.pushButton.setEnabled(True)
else:
QMessageBox.information(self, 'tip', 'no search!', QMessageBox.Ok)
def search(self):
if not self.search_running:
self.search_running = True
self.ui.pushButton.setEnabled(False)
self.search_thread = Search_Thread()
self.search_thread.trigger.connect(lambda i: self.c(i))
self.search_thread.complete.connect(self.search_complete)
self.search_thread.start()
def c(self, i):
self.ui.label.setText(str(i))
self.search_thread.resume()
def search_complete(self):
self.__thread.resume()
self.search_running = False
self.ui.pushButton.setEnabled(True)
class Search_Thread(QThread):
trigger = pyqtSignal(int)
complete = pyqtSignal()
mutex = QMutex()
cond = QWaitCondition()
def __init__(self):
super().__init__()
def run(self):
self.mutex.lock()
for i in range(10000):
for j in range(10000):
print(j)
for k in range(10000):
# time.sleep(0.1)
self.trigger.emit(i + j + k)
# time.sleep(0.1)
self.cond.wait(self.mutex)
self.complete.emit()
self.mutex.unlock()
def resume(self):
self.cond.wakeAll()
if __name__ == '__main__':
app = QApplication(sys.argv)
window = MainWindow()
screen = QDesktopWidget().screenGeometry()
height = 100
width = 300
window.setGeometry(int((screen.width() - width) / 2), int((screen.height() - height) / 2), width, height)
window.setWindowTitle("test")
window.show()
sys.exit(app.exec())
`
help me,How to improve the code so that it does not stop automatically

Related

How to close QDialog Window with pushButton?

i am currently working on this gui project. and i create a settings window but i cant make it close after pushing the buttons. i tried use self.close(), self.accept(), self.reject() methods. When i click the button nothing happens. Here is my code, which is simplified :
from PyQt5.QtWidgets import (QLineEdit, QWidget, QMenu, QMenuBar, QAction,
QMainWindow, QApplication, QDialog, QPushButton, QVBoxLayout)
from PyQt5.QtCore import QSize, QRect, QMetaObject, QCoreApplication, QObject, Qt
class Ui_Dialog(QDialog):
def __init__(self):
super(Ui_Dialog, self).__init__()
def setupUi(self, Dialog):
Dialog.setObjectName("Dialog")
Dialog.resize(100, 100)
self.verticalLayout= QVBoxLayout(Dialog)
self.lineEdit = QLineEdit(Dialog)
self.lineEdit.setObjectName("lineEdit")
self.verticalLayout.addWidget(self.lineEdit)
self.pushButton = QPushButton(Dialog)
self.pushButton.setObjectName("pushButton")
self.verticalLayout.addWidget(self.pushButton)
self.pushButton_2 = QPushButton(Dialog)
self.pushButton_2.setObjectName("pushButton_2")
self.verticalLayout.addWidget(self.pushButton_2)
self.pushButton.clicked.connect(self.close)
self.pushButton_2.clicked.connect(self.save)
self.retranslateUi(Dialog)
QMetaObject.connectSlotsByName(Dialog)
def save(self):
global setting
setting = self.lineEdit.text()
self.done(1)
self.accept()
self.deleteLater()
self.destroy()
self.reject()
self.close()
def retranslateUi(self, Dialog):
_translate = QCoreApplication.translate
Dialog.setWindowTitle(_translate("Dialog", "Settings"))
self.pushButton_2.setText(_translate("Dialog", "Save"))
self.pushButton.setText(_translate("Dialog", "Cancel"))
class Ui_MainWindow(QObject):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(1250, 609)
MainWindow.setMinimumSize(QSize(833, 600))
self.centralWidget = QWidget(MainWindow)
MainWindow.setCentralWidget(self.centralWidget)
self.centralWidget.setObjectName("centralwidget")
self.menubar = QMenuBar(MainWindow)
self.menubar.setGeometry(QRect(0, 0, 906, 21))
self.menubar.setObjectName("menubar")
self.menuOptions = QMenu(self.menubar)
self.menuOptions.setObjectName("menuOptions")
MainWindow.setMenuBar(self.menubar)
self.actionSettings = QAction(MainWindow)
self.actionSettings.setObjectName("actionSettings")
self.menuOptions.addAction(self.actionSettings)
self.menubar.addAction(self.menuOptions.menuAction())
self.actionSettings.triggered.connect(self.preferences)
self.retranslateUi(MainWindow)
QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "closinDialogSample"))
self.menuOptions.setTitle(_translate("MainWindow", "Options"))
self.actionSettings.setText(_translate("MainWindow", "Settings"))
def preferences(self):
self.preferences_dialog = QDialog()
self.preferences_dialog.ui = Ui_Dialog()
self.preferences_dialog.ui.setupUi(self.preferences_dialog)
self.preferences_dialog.setAttribute(Qt.WA_DeleteOnClose)
self.preferences_dialog.setModal(True)
self.preferences_dialog.show()
if __name__ == "__main__":
import sys
app = QApplication(sys.argv)
MainWindow = QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
Thank you for reading.

Global variable not working in dialog form

I show a dialog from main. In the dialog, I change the value of a global variable. But after the dialog closes, the global variable does not change the value.
I use PyQt5. Here is the code I call the dialog and change the variable value. I use varA to store dialog result.
def Clicked(self):
global varA
dialog = clssDialog()
dialog.exec_()
print(varA)
dialog ui
class clssDialog(QDialog):
def __init__(self):
super(clssDialog, self).__init__()
#some code
In dialog. I use:
def btnClosed(self):
global varA
varA=value
self.close()
Edit: Full code
main.py
from PyQt5 import QtCore, QtGui, QtWidgets
from dialog import *
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(219, 62)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.verticalLayout = QtWidgets.QVBoxLayout(self.centralwidget)
self.verticalLayout.setObjectName("verticalLayout")
self.pushButton = QtWidgets.QPushButton(self.centralwidget)
self.pushButton.setObjectName("pushButton")
self.pushButton.clicked.connect(self.Clicked)
self.verticalLayout.addWidget(self.pushButton)
MainWindow.setCentralWidget(self.centralwidget)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.pushButton.setText(_translate("MainWindow", "Open form"))
def Clicked(self):
global varA
varA=""
dialog = clssDialog()
dialog.exec_()
print("value: " + varA)
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
dialog.py
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
class clssDialog(QDialog):
def __init__(self):
super(clssDialog, self).__init__()
self.verticalLayout = QtWidgets.QVBoxLayout(self)
self.verticalLayout.setObjectName("verticalLayout")
self.pushButton = QtWidgets.QPushButton(self)
self.pushButton.setObjectName("pushButton")
self.pushButton.clicked.connect(self.btnClosed)
self.verticalLayout.addWidget(self.pushButton)
self.setWindowTitle("Dialog")
self.pushButton.setText("Close")
def btnClosed(self):
global varA
varA="123"
self.close()
It is not recommended to change the file created in QT Designer.
It is not necessary or advisable to use global variables. I also recommend reading Why are global variables evil?
Try it:
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
#from dialog import *
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(219, 62)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.verticalLayout = QtWidgets.QVBoxLayout(self.centralwidget)
self.verticalLayout.setObjectName("verticalLayout")
self.pushButton = QtWidgets.QPushButton(self.centralwidget)
self.pushButton.setObjectName("pushButton")
self.pushButton.clicked.connect(self.Clicked)
self.verticalLayout.addWidget(self.pushButton)
MainWindow.setCentralWidget(self.centralwidget)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.pushButton.setText(_translate("MainWindow", "Open form"))
# def Clicked(self):
# global varA
# varA=""
# dialog = ClssDialog()
# dialog.exec_()
# print("value: " + varA)
class ClssDialog(QDialog):
# def __init__(self):
# super(ClssDialog, self).__init__()
def __init__(self, parent=None):
super(ClssDialog, self).__init__(parent)
self.parent = parent
self.verticalLayout = QtWidgets.QVBoxLayout(self)
self.verticalLayout.setObjectName("verticalLayout")
self.pushButton = QtWidgets.QPushButton(self)
self.pushButton.setObjectName("pushButton")
self.pushButton.clicked.connect(self.btnClosed)
self.verticalLayout.addWidget(self.pushButton)
self.setWindowTitle("Dialog")
self.pushButton.setText("Close")
def btnClosed(self):
# global varA
self.parent.varA = "123"
self.close()
class ExampleApp(QtWidgets.QMainWindow, Ui_MainWindow):
def __init__(self):
super().__init__()
self.setupUi(self)
self.varA = ""
def Clicked(self):
# global varA
# varA=""
dialog = ClssDialog(self)
dialog.exec_()
print("value: " + self.varA)
if __name__ == "__main__":
app = QApplication(sys.argv)
view = ExampleApp()
view.show()
sys.exit(app.exec_())

Display Sensor Output on QLCDNumber using PyQT5

So I have developed a code which will detect a voltage off a transducer and then output an average voltage, my question here is how can I get this value to update as my sensor value changes, currently it is prinitng the initial value and then not updating, I created a mainwindow using QTDesigner, and I am using Python3 and PyQt5 library to write the code.
is this even possible? if so how?
This is my code:
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtGui import QPixmap
import RPi.GPIO as GPIO
import Test_rc
import time
import board
import busio
from adafruit_ads1x15.single_ended import ADS1115
i2c = busio.I2C(board.SCL,board.SDA)
adc = ADS1115(i2c)
GAIN = 2/3
c1 = 525.4
c2=28152
GPIO.setmode(GPIO.BCM)
Relay_1 = 27
Transducer = 17
GPIO.setup(Transducer,GPIO.IN)
GPIO.setup(Relay_1, GPIO.OUT)
GPIO.output(Relay_1, GPIO.HIGH)
GPIO.output(Relay_1, GPIO.LOW)
def Pressure_Reading():
while True:
time.sleep(0.02)
r0 = adc.read_volts(0,gain = GAIN, data_rate=None)
r1 = adc.read_adc(0, gain = GAIN, data_rate =None)
Pressure_Volts = r0*94.72436287
Pressure_adc = r1*(c1/c2)
time.sleep(0.02)
r01= adc.read_volts(0,gain = GAIN, data_rate=None)
r11= adc.read_adc(0, gain = GAIN, data_rate =None)
Pressure_Volts2 = r01*94.72436287
Pressure_adc2 = r11*(c1/c2)
time.sleep(0.02)
r02= adc.read_volts(0,gain = GAIN, data_rate=None)
r12= adc.read_adc(0, gain = GAIN, data_rate =None)
Pressure_Volts3 = r02*94.72436287
Pressure_adc3 = r12*(c1/c2)
time.sleep(0.02)
r03 = adc.read_volts(0,gain = GAIN, data_rate=None)
r13 = adc.read_adc(0, gain = GAIN, data_rate =None)
Pressure_Volts4 = r03*94.72436287
Pressure_adc4 = r13*(c1/c2)
time.sleep(0.02)
r04= adc.read_volts(0,gain = GAIN, data_rate=None)
r14= adc.read_adc(0, gain = GAIN, data_rate =None)
Pressure_Volts5 = r04*94.72436287
Pressure_adc5 = r14*(c1/c2)
Pressure_Volts_Avg = (Pressure_Volts+Pressure_Volts2+Pressure_Volts3+Pressure_Volts4+Pressure_Volts5)/5
Pressure_adc_Avg = (Pressure_adc+Pressure_adc2+Pressure_adc3+Pressure_adc4+Pressure_adc5)/5
Pressure_Avg = (Pressure_Volts_Avg+Pressure_adc_Avg)/2
return Pressure_Avg
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(788, 424)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.stackedWidget = QtWidgets.QStackedWidget(self.centralwidget)
self.stackedWidget.setGeometry(QtCore.QRect(10, 0, 761, 501))
self.stackedWidget.setObjectName("stackedWidget")
self.page_3 = QtWidgets.QWidget()
self.page_3.setObjectName("page_3")
self.label = QtWidgets.QLabel(self.page_3)
self.label.setGeometry(QtCore.QRect(200, 0, 341, 61))
font = QtGui.QFont()
font.setFamily("Arial Black")
font.setPointSize(22)
font.setBold(True)
font.setWeight(75)
self.label.setFont(font)
self.label.setAlignment(QtCore.Qt.AlignCenter)
self.label.setObjectName("label")
self.pushButton_2 = QtWidgets.QPushButton(self.page_3)
self.pushButton_2.setGeometry(QtCore.QRect(220, 170, 141, 41))
self.pushButton_2.setObjectName("pushButton_2")
self.pushButton = QtWidgets.QPushButton(self.page_3)
self.pushButton.setGeometry(QtCore.QRect(380, 170, 141, 41))
self.pushButton.setObjectName("pushButton")
self.label_2 = QtWidgets.QLabel(self.page_3)
self.label_2.setGeometry(QtCore.QRect(120, 260, 541, 141))
self.label_2.setObjectName("label_2")
self.groupBox_2 = QtWidgets.QGroupBox(self.page_3)
self.groupBox_2.setGeometry(QtCore.QRect(90, 40, 101, 221))
self.groupBox_2.setTitle("")
self.groupBox_2.setObjectName("groupBox_2")
self.verticalLayout_2 = QtWidgets.QVBoxLayout(self.groupBox_2)
self.verticalLayout_2.setObjectName("verticalLayout_2")
self.label_7 = QtWidgets.QLabel(self.groupBox_2)
self.label_7.setObjectName("label_7")
self.verticalLayout_2.addWidget(self.label_7)
self.lcdNumber = QtWidgets.QLCDNumber(self.groupBox_2)
self.lcdNumber.setObjectName("lcdNumber")
self.verticalLayout_2.addWidget(self.lcdNumber)
self.lcdNumber.display(Pressure_Reading())
I've input all the code up until the lcdnumber calling.
The rest of the code after the mainwindow class, I have my code control a relay and push buttons navigate a few pages, this part of the code runs fine
class ControlMainWindow(QtWidgets.QMainWindow):
def __init__(self,parent=None):
super(ControlMainWindow,self).__init__(parent)
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
self.ui.SettingsButton.clicked.connect(lambda:self.ui.stackedWidget.setCurrentIndex(1))
self.ui.pushButton_5.clicked.connect(lambda:self.ui.stackedWidget.setCurrentIndex(0))
self.ui.pushButton.clicked.connect(self.OnSwitch)
self.ui.pushButton_2.clicked.connect(self.OffSwitch)
self.ui.DelayButton.clicked.connect(self.Delay_Switch)
def OnSwitch(self):
GPIO.output(Relay_1, GPIO.HIGH)
def OffSwitch(self):
GPIO.output(Relay_1, GPIO.LOW)
def Delay_Switch(self):
time.sleep(5)
GPIO.output(Relay_1,GPIO.HIGH)
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
mySW = ControlMainWindow()
mySW.show()
sys.exit(app.exec_())
Sorry. I'm not familiar with some of the modules that you use.
In general, it might look like this:
main.py
import sys
from random import randint
from PyQt5.QtWidgets import QApplication, QMainWindow
from PyQt5.QtCore import QTimer
from ui import Ui_MainWindow
class Form(QMainWindow):
def __init__(self):
super().__init__()
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
self.i = 0
self.voltageMin = 180
self.voltageMax = 180
self.ui.lcdNumberCur.display(self.i)
self.ui.pushButton.clicked.connect(self.startTimer)
self.timer = QTimer(self)
self.timer.setInterval(1000)
self.timer.timeout.connect(self.updateData)
self.show()
def startTimer(self):
if self.ui.pushButton.text() == "Start Timer":
self.timer.start(1000)
self.ui.pushButton.setText("Stop Timer")
else:
self.ui.pushButton.setText("Start Timer")
self.timer.stop()
def updateData(self):
voltage = randint(90, 260) # <--- insert your average voltage here
self.ui.lcdNumberCur.display(voltage)
if voltage > self.voltageMax:
self.voltageMax = voltage
self.ui.lcdNumberMax.display(self.voltageMax)
elif voltage < self.voltageMin:
self.voltageMin = voltage
self.ui.lcdNumberMin.display(self.voltageMin)
if __name__ == '__main__':
app = QApplication(sys.argv)
frm = Form()
sys.exit(app.exec_())
ui.py
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(500, 300)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.groupBox = QtWidgets.QGroupBox(self.centralwidget)
self.groupBox.setGeometry(QtCore.QRect(0, 0, 400, 200))
self.groupBox.setObjectName("groupBox")
self.lcdNumberMax = QtWidgets.QLCDNumber(self.groupBox)
self.lcdNumberMax.setGeometry(QtCore.QRect(225, 10, 151, 41))
self.lcdNumberMax.setObjectName("lcdNumberMax")
self.lcdNumberCur = QtWidgets.QLCDNumber(self.groupBox)
self.lcdNumberCur.setGeometry(QtCore.QRect(225, 55, 151, 41))
self.lcdNumberCur.setObjectName("lcdNumberCur")
self.lcdNumberMin = QtWidgets.QLCDNumber(self.groupBox)
self.lcdNumberMin.setGeometry(QtCore.QRect(225, 100, 151, 41))
self.lcdNumberMin.setObjectName("lcdNumberMin")
self.label = QtWidgets.QLabel(self.groupBox)
self.label.setGeometry(QtCore.QRect(20, 50, 150, 50))
self.label.setObjectName("label")
self.labelMax = QtWidgets.QLabel(self.groupBox)
self.labelMax.setGeometry(QtCore.QRect(20, 8, 150, 50))
self.labelMax.setObjectName("labelMax")
self.labelMin = QtWidgets.QLabel(self.groupBox)
self.labelMin.setGeometry(QtCore.QRect(20, 95, 150, 50))
self.labelMin.setObjectName("labelMin")
self.pushButton = QtWidgets.QPushButton("pushButton", self.groupBox) #(self.scrollAreaWidgetContents)
self.pushButton.setGeometry(QtCore.QRect(180, 165, 75, 23))
self.pushButton.setObjectName("pushButton")
MainWindow.setCentralWidget(self.centralwidget)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "LCDNumber - Timer(Start-Stop)"))
self.groupBox.setTitle(_translate("MainWindow", "Data"))
self.label.setText(_translate("MainWindow", "Current voltage in the network"))
self.labelMin.setText(_translate("MainWindow", "Min voltage in the network"))
self.labelMax.setText(_translate("MainWindow", "Max voltage in the network"))
self.pushButton.setText(_translate("MainWindow", "Start Timer"))
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
Ok, so getting caught up in all the gui stuff, I had to implement threading and remove the functions from within the gui thread. Because the question regarded the output of the sensor I removed all the code irrelevant to it and included just the code required for the Sensor.. I hope this makes sense.
This resolved the issue:
class Worker(QtCore.QThread):
valueFound = QtCore.pyqtSignal(int, name="valueFound")
GAIN = 2/3
c1 = 525.4
c2=28152
Relay_1 = 27
def __init__(self, parent=None):
super(Worker, self).__init__(parent)
self.runFlag = False
self.i2c = busio.I2C(board.SCL,board.SDA)
self.adc = ADS1115(self.i2c)
GPIO.setmode(GPIO.BCM)
GPIO.setup(self.Relay_1, GPIO.OUT)
GPIO.output(self.Relay_1, GPIO.HIGH)
GPIO.output(self.Relay_1, GPIO.LOW)
def startThread(self):
self.runFlag = True
self.start()
def stopThread(self):
self.runFlag = False
def run(self):
while self.runFlag:
self.valueFound.emit(self.Pressure_Reading())
......
def run(self):
while self.runFlag:
self.valueFound.emit(self.Pressure_Reading())
.....
self.worker = Worker(self)
self.worker.valueFound.connect(self.OnValueFound)
.....
self.worker.startThread()
def closeEvent(self, event):
self.worker.stopThread()
while self.worker.isRunning():
pass
event.accept()
def OnValueFound(self, value):
self.ui.lcdNumber.display(value)
The addition of these allowed the program to continuously update the LCD Number.

how to use python script in pyqt5 ui widget code

I am having a pyhton script having some code as follows and and .ui file converted into the .py file. Now i want to execute the python script in widget code of gui widget?
Please help me how can i do that .
from PyQt5 import QtCore, QtGui, QtWidgets
import DC_gimbal as backend
import hudsup as hp
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(978, 600)
self.hudsup = hudsup()
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.verticalLayoutWidget = QtWidgets.QWidget(self.centralwidget)
self.verticalLayoutWidget.setGeometry(QtCore.QRect(0, 0, 291, 261))
self.verticalLayoutWidget.setObjectName("verticalLayoutWidget")
self.Heads_up = QtWidgets.QVBoxLayout(self.verticalLayoutWidget)
self.Heads_up.setContentsMargins(0, 0, 0, 0)
self.Heads_up.setObjectName("Heads_up")
self.widget = QtWidgets.QWidget(self.verticalLayoutWidget)
self.widget.setObjectName("widget")
self.HeadsWidget = QtWidgets.QWidget(self.widget)
self.HeadsWidget.setGeometry(QtCore.QRect(0, 0, 291, 261))
self.HeadsWidget.setObjectName("HeadsWidget")
self.Heads_up.addWidget(self.widget)
self.Heads_up.addWidget(self.huds_Up())
self.verticalLayoutWidget_2 = QtWidgets.QWidget(self.centralwidget)
self.verticalLayoutWidget_2.setGeometry(QtCore.QRect(0, 260, 291, 291))
self.verticalLayoutWidget_2.setObjectName("verticalLayoutWidget_2")
self.verticalLayout = QtWidgets.QVBoxLayout(self.verticalLayoutWidget_2)
self.verticalLayout.setContentsMargins(0, 0, 0, 0)
self.verticalLayout.setObjectName("verticalLayout")
self.widget_3 = QtWidgets.QWidget(self.verticalLayoutWidget_2)
self.widget_3.setObjectName("widget_3")
self.displayWidget = QtWidgets.QWidget(self.widget_3)
self.displayWidget.setGeometry(QtCore.QRect(0, 0, 291, 281))
self.displayWidget.setObjectName("displayWidget")
self.verticalLayout.addWidget(self.widget_3)
self.pushButton = QtWidgets.QPushButton(self.centralwidget)
self.pushButton.setGeometry(QtCore.QRect(500, 10, 93, 28))
self.pushButton.setObjectName("connect")
self.pushButton.clicked.connect(backend.Noctua_initialise())
self.pushButton_2 = QtWidgets.QPushButton(self.centralwidget)
self.pushButton_2.setGeometry(QtCore.QRect(620, 10, 93, 28))
self.pushButton_2.setObjectName("pushButton_2")
self.pushButton_3 = QtWidgets.QPushButton(self.centralwidget)
self.pushButton_3.setGeometry(QtCore.QRect(740, 10, 93, 28))
self.pushButton_3.setObjectName("pushButton_3")
self.tabWidget = QtWidgets.QTabWidget(self.centralwidget)
self.tabWidget.setGeometry(QtCore.QRect(290, 330, 561, 211))
self.tabWidget.setObjectName("tabWidget")
self.tab = QtWidgets.QWidget()
self.tab.setObjectName("tab")
self.tabWidget.addTab(self.tab, "")
self.tab_2 = QtWidgets.QWidget()
self.tab_2.setObjectName("tab_2")
self.tabWidget.addTab(self.tab_2, "")
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 978, 26))
self.menubar.setObjectName("menubar")
self.menuconnect = QtWidgets.QMenu(self.menubar)
self.menuconnect.setObjectName("menuconnect")
self.menuDisconnect = QtWidgets.QMenu(self.menubar)
self.menuDisconnect.setObjectName("menuDisconnect")
self.menuMode = QtWidgets.QMenu(self.menubar)
self.menuMode.setObjectName("menuMode")
self.menuSensors = QtWidgets.QMenu(self.menubar)
self.menuSensors.setObjectName("menuSensors")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.actionLIDAR = QtWidgets.QAction(MainWindow)
self.actionLIDAR.setObjectName("actionLIDAR")
self.actionOpen_CV = QtWidgets.QAction(MainWindow)
self.actionOpen_CV.setObjectName("actionOpen_CV")
self.actionManual = QtWidgets.QAction(MainWindow)
self.actionManual.setObjectName("actionManual")
self.actionAuto = QtWidgets.QAction(MainWindow)
self.actionAuto.setObjectName("actionAuto")
self.actionSettings = QtWidgets.QAction(MainWindow)
self.actionSettings.setObjectName("actionSettings")
self.actionCalib = QtWidgets.QAction(MainWindow)
self.actionCalib.setObjectName("actionCalib")
self.actionDisconnect = QtWidgets.QAction(MainWindow)
self.actionDisconnect.setObjectName("actionDisconnect")
self.menuconnect.addAction(self.actionDisconnect)
self.menuDisconnect.addAction(self.actionSettings)
self.menuDisconnect.addAction(self.actionCalib)
self.menuMode.addAction(self.actionManual)
self.menuMode.addAction(self.actionAuto)
self.menuSensors.addAction(self.actionLIDAR)
self.menuSensors.addAction(self.actionOpen_CV)
self.menubar.addAction(self.menuconnect.menuAction())
self.menubar.addAction(self.menuDisconnect.menuAction())
self.menubar.addAction(self.menuMode.menuAction())
self.menubar.addAction(self.menuSensors.menuAction())
self.retranslateUi(MainWindow)
self.tabWidget.setCurrentIndex(1)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.pushButton.setText(_translate("MainWindow", "PushButton"))
self.pushButton_2.setText(_translate("MainWindow", "PushButton"))
self.pushButton_3.setText(_translate("MainWindow", "PushButton"))
self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab), _translate("MainWindow", "Tab 1"))
self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_2), _translate("MainWindow", "Tab 2"))
self.menuconnect.setTitle(_translate("MainWindow", "connect"))
self.menuDisconnect.setTitle(_translate("MainWindow", "configure"))
self.menuMode.setTitle(_translate("MainWindow", "Mode"))
self.menuSensors.setTitle(_translate("MainWindow", "Sensors"))
self.actionLIDAR.setText(_translate("MainWindow", "LIDAR"))
self.actionOpen_CV.setText(_translate("MainWindow", "Open CV"))
self.actionManual.setText(_translate("MainWindow", "Manual"))
self.actionAuto.setText(_translate("MainWindow", "Auto"))
self.actionSettings.setText(_translate("MainWindow", "Settings"))
self.actionCalib.setText(_translate("MainWindow", "Calib"))
self.actionDisconnect.setText(_translate("MainWindow", "Disconnect"))
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
This is my gui code and i want to add the below file in the headswidget and the file name is hudsup.py :
import sys
import math
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
def rec_line_cord(i,list,xc,origin_list,pitch,roll):
.
.
def rec_drawLine(self,i,list,painter,roll,metrics):
.
.
.
def drawMarkings(self, painter):
.
.
.
def drawNeedle(self, painter,roll):
.
.
.
def Compass(self,painter,yaw,r):
.
.
.
class Manager(QObject):
changedValue = pyqtSignal(tuple)
def __init__(self):
QObject.__init__(self)
filename = "Attitude_data_Manual_1232018_1158.txt"
res = self.read_content(filename)
self.results = zip(*res)
self.timer = QTimer(self)
self.timer.timeout.connect(self.update_value)
self.timer.start(100)
#pyqtSlot()
def update_value(self):
try:
self.changedValue.emit(next(self.results))
except StopIteration:
self.timer.stop()
def read_content(self, filename):
.
.
.
class Widget(QWidget):
def __init__(self, parent=None):
QWidget.__init__(self, parent)
self.v = None
#pyqtSlot(tuple)
def update_value(self, v):
self.v = v
self.update()
def paintEvent(self, event):
QWidget.paintEvent(self, event)
painter = QPainter(self)
r = self.rect()
.
.
if __name__ == '__main__':
app = QApplication(sys.argv)
manager = Manager()
w = Widget()
manager.changedValue.connect(w.update_value)
w.show()
sys.exit(app.exec_())
This is my example of python script.
here is hudsup.py output :
animated huds_up display
and my ui looks like this and i want my hudsup to displayed as mentioned :
Gui
You should not use the generated code directly, instead, create a new widget class and inherit from it:
class MainWindow(Ui_MainWindow, QMainWindow):
def __init__(self):
Ui_MainWindow.__init__(self)
QMainWindow.__init__(self)
self.setupUi(self)
To integrate your second widget you can just add it to Heads_up like you are doing now but don't need to call exec_:
self.hud_sup = HudSup()
self.Heads_up.addWidget(self.hud_sup)

PyQt5 crashing with threading and progress bar

I have a progress bar that is controlled by a start stop button. The progress bar fills up using a thread. However, whenever I run the program it crashes at random times (different time each time program is run).
class Window(QWidget):
def __init__(self):
super().__init__()
self.initUI()
self.fill_thread = None
Thread for filling progress bar. I have tried using both time.sleep and QThread.msleep.
def fill_bar(self):
while not self.stop_fill and self.completed < 100:
self.completed += 0.5
QThread.msleep(100)
self.chargeprog.setValue(self.completed)
Buttons that alternate between start and stop that call the thread
def charging(self):
if self.chargebtn.text() == 'Start':
self.chargebtn.setText('Stop')
self.chargebtn.setStyleSheet('background-color:red')
self.fill_thread = threading.Thread(target=self.fill_bar)
self.stop_fill = False
self.fill_thread.start()
else:
self.stop_fill = True
self.fill_thread.join()
self.chargebtn.setText('Start')
self.chargebtn.setStyleSheet('background-color:limegreen')
window.py
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'window.ui'
#
# Created by: PyQt5 UI code generator 5.6
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(800, 600)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.progressBar = QtWidgets.QProgressBar(self.centralwidget)
self.progressBar.setGeometry(QtCore.QRect(180, 150, 118, 23))
self.progressBar.setProperty("value", 24)
self.progressBar.setObjectName("progressBar")
self.pushButton = QtWidgets.QPushButton(self.centralwidget)
self.pushButton.setGeometry(QtCore.QRect(330, 150, 75, 23))
self.pushButton.setObjectName("pushButton")
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 18))
self.menubar.setObjectName("menubar")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.pushButton.setText(_translate("MainWindow", "PushButton"))
test.py
import sys
from PyQt5.QtWidgets import QApplication,QMainWindow
from PyQt5.QtCore import QThread,pyqtSignal
from window import Ui_MainWindow
class CThread(QThread):
valueChanged = pyqtSignal([int])
def __init__(self,value):
super().__init__()
self.stop_fill = False
self.completed = value
def run(self):
while not self.stop_fill and self.completed < 100:
self.completed += 0.5
self.sleep(1)
self.valueChanged.emit(self.completed)
class Window(QMainWindow,Ui_MainWindow):
def __init__(self):
super().__init__()
super().setupUi(self)
self.fill_thread = None
self.pushButton.clicked.connect(self.charging)
def charging(self):
if self.pushButton.text() == 'Start':
self.pushButton.setText('Stop')
self.pushButton.setStyleSheet('background-color:red')
print(self.progressBar.value())
self.fill_thread = CThread(self.progressBar.value())
self.fill_thread.valueChanged.connect(self.progressBar.setValue)
self.fill_thread.start()
else:
if self.fill_thread != None:
self.fill_thread.disconnect() # event unbind
self.fill_thread.stop_fill = True
self.fill_thread.wait()
self.fill_thread.quit()
print(self.fill_thread.isRunning())
self.pushButton.setText('Start')
self.pushButton.setStyleSheet('background-color:limegreen')
if __name__ == '__main__':
app = QApplication(sys.argv)
w = Window()
w.show()
sys.exit(app.exec_())
If you want communicate between multi-threads, you can try signal/slots.

Resources