I am currently using the Raspberry Pi 3 to collect data from a temperature and humidity sensor (DHT11) and then display it in a QTextEdit using PyQt4.
The problem is that I would like to do this in real time but I cannot update the data automatically into the interface. Does anyone have any idea about how I can do this?
PS: Here is the link to install Adafruit if you are interested.
Have a good day,
import time
import Adafruit_DHT
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
try:
_encoding = QtGui.QApplication.UnicodeUTF8
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig)
class Ui_Room1(object):
def AffichT(self):
sensor=11
pin=4
humidity, temperature = Adafruit_DHT.read_retry(sensor, pin)
if temperature is not None:
print('Temp={0:0.1f}* Humidity={1:0.1f}%'.format(temperature, humidity))
return str(temperature)
else:
print('Failed to get reading. Try again!')
sys.exit(1)
def AffichH(self):
sensor=11
pin=4
humidity, temperature = Adafruit_DHT.read_retry(sensor, pin)
if humidity is not None:
return str(humidity)
else:
print('Failed to get reading. Try again!')
sys.exit(1)
def setupUi(self, Room1):
Room1.setObjectName(_fromUtf8("Room1"))
Room1.resize(674, 422)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(Room1.sizePolicy().hasHeightForWidth())
Room1.setSizePolicy(sizePolicy)
Room1.setMouseTracking(False)
Room1.setStyleSheet(_fromUtf8("image: url(:/gradient1/Images/gradient1.png);\n"
"\n"
""))
self.centralwidget = QtGui.QWidget(Room1)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.centralwidget.sizePolicy().hasHeightForWidth())
self.centralwidget.setSizePolicy(sizePolicy)
self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
self.graphicsView = QtGui.QGraphicsView(self.centralwidget)
self.graphicsView.setGeometry(QtCore.QRect(610, 30, 41, 41))
self.graphicsView.setStyleSheet(_fromUtf8("background-color: transparent;\n"
"background-image: url(:/gradient1/Images/logout.png);\n"
"background-repeat: no;"))
self.graphicsView.setFrameShape(QtGui.QFrame.NoFrame)
self.graphicsView.setObjectName(_fromUtf8("graphicsView"))
self.label = QtGui.QLabel(self.centralwidget)
self.label.setGeometry(QtCore.QRect(270, 50, 131, 31))
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.label.sizePolicy().hasHeightForWidth())
self.label.setSizePolicy(sizePolicy)
font = QtGui.QFont()
font.setPointSize(18)
font.setBold(True)
font.setWeight(75)
self.label.setFont(font)
self.label.setStyleSheet(_fromUtf8("image : none;\n"
"color: #fff;\n"
"background-color: transparent;"))
self.label.setObjectName(_fromUtf8("label"))
self.label_2 = QtGui.QLabel(self.centralwidget)
self.label_2.setGeometry(QtCore.QRect(140, 170, 101, 61))
self.label_2.setStyleSheet(_fromUtf8("image: none;\n"
"color: #fff;\n"
"background-color: #347;"))
self.label_2.setObjectName(_fromUtf8("label_2"))
self.label_3 = QtGui.QLabel(self.centralwidget)
self.label_3.setGeometry(QtCore.QRect(140, 260, 101, 61))
self.label_3.setStyleSheet(_fromUtf8("image: none;\n"
"color: #fff;\n"
"background-color: #347;"))
self.label_3.setObjectName(_fromUtf8("label_3"))
self.label_4 = QtGui.QLabel(self.centralwidget)
self.label_4.setGeometry(QtCore.QRect(300, 170, 101, 61))
self.label_4.setStyleSheet(_fromUtf8("image: none;\n"
"color: #fff;\n"
"background-color: #347;"))
temp = self.AffichT()
self.label_4.setText(_fromUtf8(temp+"°"))
self.label_4.setObjectName(_fromUtf8("label_4"))
self.label_5 = QtGui.QLabel(self.centralwidget)
self.label_5.setGeometry(QtCore.QRect(300, 260, 101, 61))
self.label_5.setStyleSheet(_fromUtf8("image: none;\n"
"color: #fff;\n"
"background-color: #347;"))
hum = self.AffichH()
self.label_5.setText(_fromUtf8(hum)+"%")
self.label_5.setObjectName(_fromUtf8("label_5"))
Room1.setCentralWidget(self.centralwidget)
self.retranslateUi(Room1)
QtCore.QMetaObject.connectSlotsByName(Room1)
def retranslateUi(self, Room1):
Room1.setWindowTitle(_translate("Room1", "Parents Room", None))
self.label.setText(_translate("Room1", "Welcome !", None))
self.label_2.setText(_translate("Room1", "Température:", None))
self.label_3.setText(_translate("Room1", "Humidité:", None))
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
Room1 = QtGui.QMainWindow()
ui = Ui_Room1()
ui.setupUi(Room1)
Room1.show()
sys.exit(app.exec_())`
The following must be taken into account:
Reading a temperature sensor takes time, in the case of DHT it consumes 2 seconds, this is not a general disadvantage since the ambient temperature does not vary rapidly.
As the reading task is very time consuming, it should not be executed in the main thread but in a secondary one and send the information through signals.
import time
import threading
import Adafruit_DHT
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
try:
_encoding = QtGui.QApplication.UnicodeUTF8
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig)
class Ui_Room1(object):
def setupUi(self, Room1):
Room1.setObjectName(_fromUtf8("Room1"))
Room1.resize(674, 422)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(Room1.sizePolicy().hasHeightForWidth())
Room1.setSizePolicy(sizePolicy)
Room1.setMouseTracking(False)
Room1.setStyleSheet(
_fromUtf8("image: url(:/gradient1/Images/gradient1.png);\n" "\n" "")
)
self.centralwidget = QtGui.QWidget(Room1)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.centralwidget.sizePolicy().hasHeightForWidth()
)
self.centralwidget.setSizePolicy(sizePolicy)
self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
self.graphicsView = QtGui.QGraphicsView(self.centralwidget)
self.graphicsView.setGeometry(QtCore.QRect(610, 30, 41, 41))
self.graphicsView.setStyleSheet(
_fromUtf8(
"background-color: transparent;\n"
"background-image: url(:/gradient1/Images/logout.png);\n"
"background-repeat: no;"
)
)
self.graphicsView.setFrameShape(QtGui.QFrame.NoFrame)
self.graphicsView.setObjectName(_fromUtf8("graphicsView"))
self.label = QtGui.QLabel(self.centralwidget)
self.label.setGeometry(QtCore.QRect(270, 50, 131, 31))
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.label.sizePolicy().hasHeightForWidth())
self.label.setSizePolicy(sizePolicy)
font = QtGui.QFont()
font.setPointSize(18)
font.setBold(True)
font.setWeight(75)
self.label.setFont(font)
self.label.setStyleSheet(
_fromUtf8(
"image : none;\n" "color: #fff;\n" "background-color: transparent;"
)
)
self.label.setObjectName(_fromUtf8("label"))
self.label_2 = QtGui.QLabel(self.centralwidget)
self.label_2.setGeometry(QtCore.QRect(140, 170, 101, 61))
self.label_2.setStyleSheet(
_fromUtf8("image: none;\n" "color: #fff;\n" "background-color: #347;")
)
self.label_2.setObjectName(_fromUtf8("label_2"))
self.label_3 = QtGui.QLabel(self.centralwidget)
self.label_3.setGeometry(QtCore.QRect(140, 260, 101, 61))
self.label_3.setStyleSheet(
_fromUtf8("image: none;\n" "color: #fff;\n" "background-color: #347;")
)
self.label_3.setObjectName(_fromUtf8("label_3"))
self.label_4 = QtGui.QLabel(self.centralwidget)
self.label_4.setGeometry(QtCore.QRect(300, 170, 101, 61))
self.label_4.setStyleSheet(
_fromUtf8("image: none;\n" "color: #fff;\n" "background-color: #347;")
)
self.label_4.setObjectName(_fromUtf8("label_4"))
self.label_5 = QtGui.QLabel(self.centralwidget)
self.label_5.setGeometry(QtCore.QRect(300, 260, 101, 61))
self.label_5.setStyleSheet(
_fromUtf8("image: none;\n" "color: #fff;\n" "background-color: #347;")
)
self.label_5.setObjectName(_fromUtf8("label_5"))
Room1.setCentralWidget(self.centralwidget)
self.retranslateUi(Room1)
QtCore.QMetaObject.connectSlotsByName(Room1)
def retranslateUi(self, Room1):
Room1.setWindowTitle(_translate("Room1", "Parents Room", None))
self.label.setText(_translate("Room1", "Welcome !", None))
self.label_2.setText(_translate("Room1", "Température:", None))
self.label_3.setText(_translate("Room1", "Humidité:", None))
class Adafruit_DHT_Worker(QtCore.QObject):
valueChanged = QtCore.pyqtSignal(float, float)
def start(self):
threading.Thread(target=self._read, daemon=True).start()
def _read(self):
sensor=11
pin=4
humidity, temperature = Adafruit_DHT.read_retry(sensor, pin)
if humidity is not None and temperature is not None:
self.valueChanged.emit(temperature, humidity)
class Room1(QtGui.QMainWindow, Ui_Room1):
def __init__(self, parent=None):
super().__init__(parent)
self.setupUi(self)
self.dht_worker = Adafruit_DHT_Worker()
self.dht_worker.valueChanged.connect(self.on_value_changed)
self.dht_worker.start()
#QtCore.pyqtSlot(float, float)
def on_value_changed(self, humidity, temperature):
self.label_4.setNum(temperature)
self.label_5.setNum(humidity)
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
w = Room1()
w.show()
sys.exit(app.exec_())
Related
I am trying to build an AI voice recognition app with a GUI to show the speech recognition text as well as my pre-determined outcomes as a text inside different labels in pyqt6 program. the problem is how do I set the label's text to change dynamically based on the the recognized speech (output as text) and next step of the AI's predetermined outcome(also output as text) on the pyqt app labels.
A normal import of the AI.py file into the QT6.py file doesn't dynamically change the text.
Combining both into the same file runs either the program (which has nested loops to carry outcomes based on user's speech query) or the pyqt window whichever is run earlier. the combined file doesn't run one after the other.
What I am looking to acheive:
labels inside pyqt app window to change and show text dynamically based on how the text output changes in the AI app.
Here is my qt6.py child file:
from main_ui import UI_Extension
from PyQt6 import QtWidgets
import sys
class U_interface(UI_Extension):
def setupUi(self, Form):
super().setupUi(Form)
self.alerts.setText("Liability Warning")
self.alert_description.setText("Liability description")
self.ai_response.setText(Dynamic_text) # from AI.py file
self.mic_recording_state.setText("Listening...(test)")
self.speech_recognition.setText(Dynamic_speech_recognition_text) # from AI.py file
self.management_plan.setText("EKG scheduled for the 24th of November 2022")
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
Form = QtWidgets.QWidget()
ui = U_interface()
ui.setupUi(Form)
Form.show()
sys.exit(app.exec())
Here is my qt6.py parent file converted from qt_designer .ui file
from PyQt6 import QtCore, QtGui, QtWidgets
class Ui_Form(object):
def setupUi(self, Form):
Form.setObjectName("Form")
Form.resize(1280, 800)
Form.setAutoFillBackground(False)
Form.setStyleSheet("")
self.combined_layout = QtWidgets.QWidget(Form)
self.combined_layout.setGeometry(QtCore.QRect(0, 0, 1280, 800))
self.combined_layout.setStyleSheet("QPushButton#ReviewCase{\n"
" background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:1, stop:0 rgba(33, 124, 173, 255), stop:1 rgba(31, 118, 165, 142));\n"
" color:rgba(255,255,255,210);\n"
" border-radius: 5px;\n"
"}\n"
"\n"
"QPushButton#ReviewCase:hover{\n"
" background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:1, stop:0 rgba(14, 208, 75, 255), stop:1 rgba(26, 255, 0, 213));\n"
" color:rgba(255,255,255,210);\n"
" color:rgba(0,0,0,210);\n"
"}\n"
"\n"
"QPushButton#ReviewCase:pressed{\n"
" padding-left:5px;\n"
" padding-right:5px;\n"
" color:rgba(255,255,255,210);\n"
" background-color: rgba(105,118,132,200);\n"
"}\n"
"\n"
"QPushButton#ExitProgram{\n"
" background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:1, stop:0 rgba(33, 124, 173, 255), stop:1 rgba(31, 118, 165, 142));\n"
" color:rgba(255,255,255,210);\n"
" border-radius: 5px;\n"
"}\n"
"\n"
"QPushButton#ExitProgram:hover{\n"
" background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:1, stop:0 rgba(255, 0, 4, 255), stop:1 rgba(255, 0, 0, 111));\n"
" color:rgba(255,255,255,210);\n"
"}\n"
"\n"
"QPushButton#ExitProgram:pressed{\n"
" padding-left:5px;\n"
" padding-right:5px;\n"
" background-color: rgba(105,118,132,200);\n"
"}\n"
"")
self.combined_layout.setObjectName("combined_layout")
self.background_image = QtWidgets.QLabel(self.combined_layout)
self.background_image.setGeometry(QtCore.QRect(0, 0, 1280, 800))
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Policy.Ignored, QtWidgets.QSizePolicy.Policy.Ignored)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.background_image.sizePolicy().hasHeightForWidth())
self.background_image.setSizePolicy(sizePolicy)
font = QtGui.QFont()
font.setPointSize(10)
self.background_image.setFont(font)
self.background_image.setContextMenuPolicy(QtCore.Qt.ContextMenuPolicy.DefaultContextMenu)
self.background_image.setStyleSheet("border-image: url(:/images/background);")
self.background_image.setText("")
self.background_image.setScaledContents(True)
self.background_image.setObjectName("background_image")
self.doc_logo = QtWidgets.QLabel(self.combined_layout)
self.doc_logo.setGeometry(QtCore.QRect(15, 16, 41, 41))
self.doc_logo.setStyleSheet("border-image: url(:/images/doctor);")
self.doc_logo.setText("")
self.doc_logo.setObjectName("doc_logo")
self.horizontalLayoutWidget = QtWidgets.QWidget(self.combined_layout)
self.horizontalLayoutWidget.setGeometry(QtCore.QRect(10, 743, 1261, 51))
self.horizontalLayoutWidget.setObjectName("horizontalLayoutWidget")
self.horizontalLayout = QtWidgets.QHBoxLayout(self.horizontalLayoutWidget)
self.horizontalLayout.setSizeConstraint(QtWidgets.QLayout.SizeConstraint.SetDefaultConstraint)
self.horizontalLayout.setContentsMargins(5, 0, 5, 0)
self.horizontalLayout.setSpacing(10)
self.horizontalLayout.setObjectName("horizontalLayout")
self.ExitProgram = QtWidgets.QPushButton(self.horizontalLayoutWidget)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Policy.Maximum, QtWidgets.QSizePolicy.Policy.Maximum)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.ExitProgram.sizePolicy().hasHeightForWidth())
self.ExitProgram.setSizePolicy(sizePolicy)
self.ExitProgram.setMinimumSize(QtCore.QSize(200, 35))
self.ExitProgram.setBaseSize(QtCore.QSize(0, 0))
font = QtGui.QFont()
font.setPointSize(13)
font.setBold(True)
font.setKerning(True)
self.ExitProgram.setFont(font)
self.ExitProgram.setCursor(QtGui.QCursor(QtCore.Qt.CursorShape.PointingHandCursor))
self.ExitProgram.setStyleSheet("")
self.ExitProgram.setObjectName("ExitProgram")
self.horizontalLayout.addWidget(self.ExitProgram)
spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Policy.Expanding, QtWidgets.QSizePolicy.Policy.Minimum)
self.horizontalLayout.addItem(spacerItem)
self.mic_recording_state = QtWidgets.QLabel(self.horizontalLayoutWidget)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Policy.Minimum, QtWidgets.QSizePolicy.Policy.Minimum)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.mic_recording_state.sizePolicy().hasHeightForWidth())
self.mic_recording_state.setSizePolicy(sizePolicy)
self.mic_recording_state.setMinimumSize(QtCore.QSize(770, 25))
font = QtGui.QFont()
font.setPointSize(20)
font.setBold(False)
self.mic_recording_state.setFont(font)
self.mic_recording_state.setStyleSheet("color: #c6d4e2;")
self.mic_recording_state.setText("")
self.mic_recording_state.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter)
self.mic_recording_state.setIndent(0)
self.mic_recording_state.setObjectName("mic_recording_state")
self.horizontalLayout.addWidget(self.mic_recording_state)
spacerItem1 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Policy.Expanding, QtWidgets.QSizePolicy.Policy.Minimum)
self.horizontalLayout.addItem(spacerItem1)
self.ReviewCase = QtWidgets.QPushButton(self.horizontalLayoutWidget)
self.ReviewCase.setEnabled(True)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Policy.Maximum, QtWidgets.QSizePolicy.Policy.Maximum)
sizePolicy.setHorizontalStretch(60)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.ReviewCase.sizePolicy().hasHeightForWidth())
self.ReviewCase.setSizePolicy(sizePolicy)
self.ReviewCase.setMinimumSize(QtCore.QSize(200, 35))
font = QtGui.QFont()
font.setPointSize(13)
font.setBold(True)
self.ReviewCase.setFont(font)
self.ReviewCase.setCursor(QtGui.QCursor(QtCore.Qt.CursorShape.PointingHandCursor))
self.ReviewCase.setAutoFillBackground(False)
self.ReviewCase.setStyleSheet("")
self.ReviewCase.setObjectName("ReviewCase")
self.horizontalLayout.addWidget(self.ReviewCase)
self.layoutWidget = QtWidgets.QWidget(self.combined_layout)
self.layoutWidget.setGeometry(QtCore.QRect(100, 40, 661, 681))
self.layoutWidget.setObjectName("layoutWidget")
self.verticalLayout = QtWidgets.QVBoxLayout(self.layoutWidget)
self.verticalLayout.setContentsMargins(0, 0, 0, 0)
self.verticalLayout.setSpacing(20)
self.verticalLayout.setObjectName("verticalLayout")
self.alerts = QtWidgets.QLabel(self.layoutWidget)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Policy.Preferred, QtWidgets.QSizePolicy.Policy.Minimum)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.alerts.sizePolicy().hasHeightForWidth())
self.alerts.setSizePolicy(sizePolicy)
self.alerts.setMinimumSize(QtCore.QSize(0, 50))
font = QtGui.QFont()
font.setFamily("Cambria")
font.setPointSize(22)
font.setBold(True)
self.alerts.setFont(font)
self.alerts.setToolTip("")
self.alerts.setStyleSheet("color: rgb(255, 116, 69);")
self.alerts.setText("")
self.alerts.setAlignment(QtCore.Qt.AlignmentFlag.AlignHCenter|QtCore.Qt.AlignmentFlag.AlignTop)
self.alerts.setIndent(0)
self.alerts.setObjectName("alerts")
self.verticalLayout.addWidget(self.alerts)
self.alert_description = QtWidgets.QLabel(self.layoutWidget)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Policy.Preferred, QtWidgets.QSizePolicy.Policy.Minimum)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.alert_description.sizePolicy().hasHeightForWidth())
self.alert_description.setSizePolicy(sizePolicy)
self.alert_description.setMinimumSize(QtCore.QSize(0, 50))
font = QtGui.QFont()
font.setPointSize(22)
font.setBold(True)
self.alert_description.setFont(font)
self.alert_description.setStyleSheet("color: rgb(43, 255, 121);")
self.alert_description.setText("")
self.alert_description.setAlignment(QtCore.Qt.AlignmentFlag.AlignHCenter|QtCore.Qt.AlignmentFlag.AlignTop)
self.alert_description.setIndent(0)
self.alert_description.setObjectName("alert_description")
self.verticalLayout.addWidget(self.alert_description)
self.ai_response = QtWidgets.QLabel(self.layoutWidget)
font = QtGui.QFont()
font.setFamily("Cambria")
font.setPointSize(22)
font.setBold(False)
self.ai_response.setFont(font)
self.ai_response.setStyleSheet("padding: 23 33 23;\n"
"color: #c6d4e2;\n"
"\n"
"")
self.ai_response.setFrameShape(QtWidgets.QFrame.Shape.NoFrame)
self.ai_response.setLineWidth(1)
self.ai_response.setText("")
self.ai_response.setScaledContents(False)
self.ai_response.setAlignment(QtCore.Qt.AlignmentFlag.AlignJustify|QtCore.Qt.AlignmentFlag.AlignVCenter)
self.ai_response.setWordWrap(True)
self.ai_response.setIndent(0)
self.ai_response.setObjectName("ai_response")
self.verticalLayout.addWidget(self.ai_response)
self.horizontalLayout_2 = QtWidgets.QHBoxLayout()
self.horizontalLayout_2.setSpacing(0)
self.horizontalLayout_2.setObjectName("horizontalLayout_2")
self.gif = QtWidgets.QLabel(self.layoutWidget)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Policy.Ignored, QtWidgets.QSizePolicy.Policy.Ignored)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.gif.sizePolicy().hasHeightForWidth())
self.gif.setSizePolicy(sizePolicy)
self.gif.setMinimumSize(QtCore.QSize(240, 180))
self.gif.setStyleSheet("")
self.gif.setText("")
self.gif.setScaledContents(True)
self.gif.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter)
self.gif.setIndent(0)
self.gif.setObjectName("gif")
self.horizontalLayout_2.addWidget(self.gif)
self.speech_recognition = QtWidgets.QLabel(self.layoutWidget)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Policy.Preferred, QtWidgets.QSizePolicy.Policy.Minimum)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(170)
sizePolicy.setHeightForWidth(self.speech_recognition.sizePolicy().hasHeightForWidth())
self.speech_recognition.setSizePolicy(sizePolicy)
self.speech_recognition.setMinimumSize(QtCore.QSize(0, 170))
font = QtGui.QFont()
font.setPointSize(16)
self.speech_recognition.setFont(font)
self.speech_recognition.setStyleSheet("padding: 29 33 29;\n"
"color: #c6d4e2;")
self.speech_recognition.setText("")
self.speech_recognition.setAlignment(QtCore.Qt.AlignmentFlag.AlignJustify|QtCore.Qt.AlignmentFlag.AlignVCenter)
self.speech_recognition.setWordWrap(True)
self.speech_recognition.setIndent(0)
self.speech_recognition.setTextInteractionFlags(QtCore.Qt.TextInteractionFlag.NoTextInteraction)
self.speech_recognition.setObjectName("speech_recognition")
self.horizontalLayout_2.addWidget(self.speech_recognition)
self.horizontalLayout_2.setStretch(0, 3)
self.horizontalLayout_2.setStretch(1, 6)
self.verticalLayout.addLayout(self.horizontalLayout_2)
self.verticalLayout.setStretch(0, 1)
self.verticalLayout.setStretch(2, 6)
self.verticalLayout.setStretch(3, 4)
self.layoutWidget1 = QtWidgets.QWidget(self.combined_layout)
self.layoutWidget1.setGeometry(QtCore.QRect(850, 40, 411, 681))
self.layoutWidget1.setObjectName("layoutWidget1")
self.verticalLayout_2 = QtWidgets.QVBoxLayout(self.layoutWidget1)
self.verticalLayout_2.setContentsMargins(0, 0, 0, 0)
self.verticalLayout_2.setSpacing(15)
self.verticalLayout_2.setObjectName("verticalLayout_2")
self.management = QtWidgets.QLabel(self.layoutWidget1)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Policy.Preferred, QtWidgets.QSizePolicy.Policy.Minimum)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.management.sizePolicy().hasHeightForWidth())
self.management.setSizePolicy(sizePolicy)
self.management.setMinimumSize(QtCore.QSize(0, 50))
self.management.setStyleSheet("font: 700 22pt \"Segoe UI Variable Text\";\n"
"color: rgb(153, 255, 199);")
self.management.setAlignment(QtCore.Qt.AlignmentFlag.AlignHCenter|QtCore.Qt.AlignmentFlag.AlignTop)
self.management.setIndent(0)
self.management.setObjectName("management")
self.verticalLayout_2.addWidget(self.management)
self.management_plan = QtWidgets.QTextBrowser(self.layoutWidget1)
font = QtGui.QFont()
font.setPointSize(18)
font.setBold(True)
self.management_plan.setFont(font)
self.management_plan.viewport().setProperty("cursor", QtGui.QCursor(QtCore.Qt.CursorShape.ArrowCursor))
self.management_plan.setStyleSheet("background-color: rgb(7, 18, 40);\n"
"border-radius: 10px;\n"
"padding: 25 25 25 25;\n"
"color: #c6d4e2;")
self.management_plan.setInputMethodHints(QtCore.Qt.InputMethodHint.ImhMultiLine)
self.management_plan.setTextInteractionFlags(QtCore.Qt.TextInteractionFlag.LinksAccessibleByKeyboard|QtCore.Qt.TextInteractionFlag.LinksAccessibleByMouse|QtCore.Qt.TextInteractionFlag.TextBrowserInteraction|QtCore.Qt.TextInteractionFlag.TextSelectableByKeyboard|QtCore.Qt.TextInteractionFlag.TextSelectableByMouse)
self.management_plan.setOpenExternalLinks(True)
self.management_plan.setObjectName("management_plan")
self.verticalLayout_2.addWidget(self.management_plan)
self.verticalLayout_2.setStretch(0, 1)
self.verticalLayout_2.setStretch(1, 12)
self.retranslateUi(Form)
QtCore.QMetaObject.connectSlotsByName(Form)
def retranslateUi(self, Form):
_translate = QtCore.QCoreApplication.translate
Form.setWindowTitle(_translate("Form", "Form"))
self.ExitProgram.setText(_translate("Form", "Exit Program"))
self.ReviewCase.setText(_translate("Form", "Review Case"))
self.management.setText(_translate("Form", "Management"))
self.management_plan.setHtml(_translate("Form", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
"<html><head><meta name=\"qrichtext\" content=\"1\" /><meta charset=\"utf-8\" /><style type=\"text/css\">\n"
"p, li { white-space: pre-wrap; }\n"
"hr { height: 1px; border-width: 0; }\n"
"</style></head><body style=\" font-family:\'Segoe UI Variable Text\'; font-size:18pt; font-weight:700; font-style:normal;\">\n"
"<p style=\"-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-size:14pt;\"><br /></p></body></html>"))
Here is my AI.py file:
from playsound import playsound
import sounddevice as sd
from gtts import gTTS
import argparse
import random
import queue
import vosk
import json
import sys
import os
q = queue.Queue()
model = vosk.Model("c:......Model (EN-US)")
def greeting():
..........
def microphone():
..........
speech_recognition_text = "xyz........" # to be printed inside the label in qt6.py file
def recorded_audio():
............
def speak(transcription):
............
try:
............
stream = sd.RawInputStream(samplerate=args.samplerate, blocksize = 8000, device=args.device, dtype='int16', channels=1, callback=callback)
with stream:
greeting()
while True:
audio = recorded_audio()
if ('hello' in audio):
Dynamic_text = "abc...." # to be printed inside the label in qt6.py file
elif ('all right' in audio):
DynamicText = "def......" # to be printed inside the label in qt6.py file
except KeyboardInterrupt:
print('\nShutting Down')
parser.exit(0)
except Exception as e:
parser.exit(type(e).__name__ + ': ' + str(e))
I am under the impression that QThread is to be used somehow. Dont know how and where.
Any help is greatly appreciated.
I don't understand how to put data into QTableWidget row by row. I take data from lineEdit then put it into table, but when I try to add another person with data it rewrites the previous data, but I need to put it in the row below. I guess I should do something with "row"
Here is my code
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtGui import *
import sqlite3
import sys
conn = sqlite3.connect('todo.db')
cur = conn.cursor()
cur.execute('CREATE TABLE if not exists disp_list(disp_name text, disp_surname text, disp_date text)')
conn.commit()
conn.close()
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(960, 550)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.listWidget = QtWidgets.QListWidget(self.centralwidget)
self.listWidget.setGeometry(QtCore.QRect(610, 261, 341, 241))
self.listWidget.setObjectName("listWidget")
self.label = QtWidgets.QLabel(self.centralwidget)
self.label.setGeometry(QtCore.QRect(610, 180, 331, 71))
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(14)
self.label.setFont(font)
self.label.setWordWrap(True)
self.label.setObjectName("label")
self.lineEdit = QtWidgets.QLineEdit(self.centralwidget)
self.lineEdit.setGeometry(QtCore.QRect(10, 40, 311, 41))
self.lineEdit.setObjectName("lineEdit")
self.lineEdit_2 = QtWidgets.QLineEdit(self.centralwidget)
self.lineEdit_2.setGeometry(QtCore.QRect(340, 40, 311, 41))
self.lineEdit_2.setObjectName("lineEdit_2")
self.lineEdit_3 = QtWidgets.QLineEdit(self.centralwidget)
self.lineEdit_3.setGeometry(QtCore.QRect(690, 40, 251, 41))
self.lineEdit_3.setObjectName("lineEdit_3")
self.pushButton = QtWidgets.QPushButton(self.centralwidget, clicked=lambda: self.add_disp())
self.pushButton.setGeometry(QtCore.QRect(30, 100, 221, 71))
font = QtGui.QFont()
font.setFamily("Times New Roman")
font.setPointSize(14)
font.setBold(False)
font.setWeight(50)
self.pushButton.setFont(font)
self.pushButton.setObjectName("pushButton")
self.pushButton_3 = QtWidgets.QPushButton(self.centralwidget)
self.pushButton_3.setGeometry(QtCore.QRect(270, 100, 221, 71))
font = QtGui.QFont()
font.setFamily("Times New Roman")
font.setPointSize(14)
font.setBold(False)
font.setWeight(50)
self.pushButton_3.setFont(font)
self.pushButton_3.setObjectName("pushButton_3")
self.pushButton_4 = QtWidgets.QPushButton(self.centralwidget)
self.pushButton_4.setGeometry(QtCore.QRect(720, 100, 221, 71))
font = QtGui.QFont()
font.setFamily("Times New Roman")
font.setPointSize(14)
font.setBold(False)
font.setWeight(50)
self.pushButton_4.setFont(font)
self.pushButton_4.setObjectName("pushButton_4")
self.tableWidget = QtWidgets.QTableWidget(self.centralwidget)
self.tableWidget.setGeometry(QtCore.QRect(10, 200, 591, 301))
self.tableWidget.setRowCount(130)
self.tableWidget.setObjectName("tableWidget")
self.tableWidget.setColumnCount(3)
item = QtWidgets.QTableWidgetItem()
font = QtGui.QFont()
font.setPointSize(18)
item.setFont(font)
self.tableWidget.setVerticalHeaderItem(0, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setHorizontalHeaderItem(0, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setHorizontalHeaderItem(1, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setHorizontalHeaderItem(2, item)
self.tableWidget.horizontalHeader().setDefaultSectionSize(180)
self.label_2 = QtWidgets.QLabel(self.centralwidget)
self.label_2.setGeometry(QtCore.QRect(20, 10, 291, 16))
font = QtGui.QFont()
font.setFamily("Arial Black")
font.setPointSize(14)
font.setBold(True)
font.setWeight(75)
self.label_2.setFont(font)
self.label_2.setObjectName("label_2")
self.label_3 = QtWidgets.QLabel(self.centralwidget)
self.label_3.setGeometry(QtCore.QRect(350, 10, 291, 16))
font = QtGui.QFont()
font.setFamily("Arial Black")
font.setPointSize(14)
font.setBold(True)
font.setWeight(75)
self.label_3.setFont(font)
self.label_3.setObjectName("label_3")
self.label_4 = QtWidgets.QLabel(self.centralwidget)
self.label_4.setGeometry(QtCore.QRect(690, 10, 251, 20))
font = QtGui.QFont()
font.setFamily("Arial Black")
font.setPointSize(16)
font.setBold(True)
font.setWeight(75)
self.label_4.setFont(font)
self.label_4.setObjectName("label_4")
self.pushButton_5 = QtWidgets.QPushButton(self.centralwidget)
self.pushButton_5.setGeometry(QtCore.QRect(510, 100, 191, 71))
font = QtGui.QFont()
font.setFamily("Times New Roman")
font.setPointSize(14)
font.setBold(False)
font.setWeight(50)
self.pushButton_5.setFont(font)
self.pushButton_5.setObjectName("pushButton_5")
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 960, 21))
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 add_disp(self):
name = self.lineEdit.text()
surname = self.lineEdit_2.text()
date = self.lineEdit_3.text()
disps=[{"disp_name": name, "disp_surname": surname, "disp_date": date}]
for person in disps:
row = 1
self.tableWidget.setItem(row, 0, QtWidgets.QTableWidgetItem(person["disp_name"]))
self.tableWidget.setItem(row, 1, QtWidgets.QTableWidgetItem(person["disp_surname"]))
self.tableWidget.setItem(row, 2, QtWidgets.QTableWidgetItem(person["disp_date"]))
name = self.lineEdit.setText("")
surname = self.lineEdit_2.setText("")
date = self.lineEdit_3.setText("")
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.label.setText(_translate("MainWindow", "Список диспетчеров, у которых заканчивается срок"))
self.pushButton.setText(_translate("MainWindow", "Add ATC"))
self.pushButton_3.setText(_translate("MainWindow", "Delete from table"))
self.pushButton_4.setText(_translate("MainWindow", "Delete from database"))
item = self.tableWidget.horizontalHeaderItem(0)
item.setText(_translate("MainWindow", "Name"))
item = self.tableWidget.horizontalHeaderItem(1)
item.setText(_translate("MainWindow", "Surname"))
item = self.tableWidget.horizontalHeaderItem(2)
item.setText(_translate("MainWindow", "Issue_date"))
self.label_2.setText(_translate("MainWindow", "Enter name"))
self.label_3.setText(_translate("MainWindow", "Enter surname"))
self.label_4.setText(_translate("MainWindow", "Enter date"))
self.pushButton_5.setText(_translate("MainWindow", "Save to database"))
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_())
Supposing that you want to insert items incrementally, you should create an instance attribute that will be used to start with the first row (which is 0, not 1, by the way) and then increment it by 1 every time.
This, anyway, should not be done with a file created by pyuic, because those files are meant to be left unmodified. Editing them is highly discouraged and considered bad practice for a lot of reasons. Read more about how to properly use those files when using Designer.
So, rebuild again your .ui file (in the next example I'm supposing you've generated a file named ui_mainwindow.py), and then create your actual script similar to the following:
from PyQt5 import QtCore, QtGui, QtWidgets
from ui_mainwindow import Ui_MainWindow
import sqlite3
import sys
conn = sqlite3.connect('todo.db')
cur = conn.cursor()
cur.execute('CREATE TABLE if not exists disp_list(disp_name text, disp_surname text, disp_date text)')
conn.commit()
conn.close()
class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
def __init__(self):
super().__init__()
self.setupUi(self)
self.currentRow = -1
self.pushButton.clicked.connect(self.add_disp)
def add_disp(self):
name = self.lineEdit.text()
surname = self.lineEdit_2.text()
date = self.lineEdit_3.text()
self.currentRow += 1
if self.currentRow > self.tableWidget.rowCount() - 1:
self.tableWidget.insertRow(self.tableWidget.rowCount())
self.tableWidget.setItem(self.currentRow, 0,
QtWidgets.QTableWidgetItem(name))
self.tableWidget.setItem(self.currentRow, 1,
QtWidgets.QTableWidgetItem(surname))
self.tableWidget.setItem(self.currentRow, 2,
QtWidgets.QTableWidgetItem(date))
self.lineEdit.clear()
self.lineEdit_2.clear()
self.lineEdit_3.clear()
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
mainWindow = MainWindow()
mainWindow.show()
sys.exit(app.exec_())
Good day, Please can someone assist, i have to add 2 calendars to my U.I, a birthday calendar and a 2019 calendar.
When i run the python script i don't receive any errors, nothing happens. It doesn't display the U.I design.
The first code is the .ui converted to .py and the code thereafter is the code to invoke and display the U.I Design, but nothing happens, please can someone help me, i am new to Python and i am really struggling.
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
try:
_encoding = QtGui.QApplication.UnicodeUTF8
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig)
class Ui_Dialog(object):
def setupUi(self, Dialog):
Dialog.setObjectName(_fromUtf8("Dialog"))
Dialog.resize(704, 580)
self.calendarWidget = QtGui.QCalendarWidget(Dialog)
self.calendarWidget.setGeometry(QtCore.QRect(190, 10, 280, 155))
font = QtGui.QFont()
font.setFamily(_fromUtf8("Script MT Bold"))
font.setBold(True)
font.setItalic(False)
font.setWeight(75)
self.calendarWidget.setFont(font)
self.calendarWidget.setObjectName(_fromUtf8("calendarWidget"))
self.calendarWidget_2 = QtGui.QCalendarWidget(Dialog)
self.calendarWidget_2.setGeometry(QtCore.QRect(190, 220, 280, 155))
font = QtGui.QFont()
font.setFamily(_fromUtf8("Script MT Bold"))
font.setBold(True)
font.setWeight(75)
self.calendarWidget_2.setFont(font)
self.calendarWidget_2.setSelectedDate(QtCore.QDate(2019, 3, 27))
self.calendarWidget_2.setObjectName(_fromUtf8("calendarWidget_2"))
self.label = QtGui.QLabel(Dialog)
self.label.setGeometry(QtCore.QRect(10, 220, 101, 20))
self.label.setObjectName(_fromUtf8("label"))
self.dateEdit = QtGui.QDateEdit(Dialog)
self.dateEdit.setGeometry(QtCore.QRect(280, 380, 91, 21))
self.dateEdit.setDateTime(QtCore.QDateTime(QtCore.QDate(2019, 3, 27), QtCore.QTime(0, 0, 0)))
self.dateEdit.setDate(QtCore.QDate(2019, 3, 27))
self.dateEdit.setObjectName(_fromUtf8("dateEdit"))
self.dateEdit_2 = QtGui.QDateEdit(Dialog)
self.dateEdit_2.setGeometry(QtCore.QRect(280, 170, 91, 21))
self.dateEdit_2.setDate(QtCore.QDate(2019, 2, 22))
self.dateEdit_2.setObjectName(_fromUtf8("dateEdit_2"))
self.label_2 = QtGui.QLabel(Dialog)
self.label_2.setGeometry(QtCore.QRect(10, 20, 71, 20))
self.label_2.setObjectName(_fromUtf8("label_2"))
self.label_3 = QtGui.QLabel(Dialog)
self.label_3.setGeometry(QtCore.QRect(530, 510, 141, 16))
self.label_3.setObjectName(_fromUtf8("label_3"))
self.label_4 = QtGui.QLabel(Dialog)
self.label_4.setGeometry(QtCore.QRect(530, 530, 111, 16))
self.label_4.setObjectName(_fromUtf8("label_4"))
self.pushButton = QtGui.QPushButton(Dialog)
self.pushButton.setGeometry(QtCore.QRect(280, 430, 91, 23))
self.pushButton.setObjectName(_fromUtf8("pushButton"))
self.label_5 = QtGui.QLabel(Dialog)
self.label_5.setGeometry(QtCore.QRect(10, 380, 181, 16))
self.label_5.setObjectName(_fromUtf8("label_5"))
self.label_6 = QtGui.QLabel(Dialog)
self.label_6.setGeometry(QtCore.QRect(10, 460, 81, 16))
self.label_6.setObjectName(_fromUtf8("label_6"))
self.lineEdit = QtGui.QLineEdit(Dialog)
self.lineEdit.setGeometry(QtCore.QRect(280, 460, 91, 20))
self.lineEdit.setObjectName(_fromUtf8("lineEdit"))
self.label_7 = QtGui.QLabel(Dialog)
self.label_7.setGeometry(QtCore.QRect(10, 170, 91, 16))
self.label_7.setObjectName(_fromUtf8("label_7"))
self.label_8 = QtGui.QLabel(Dialog)
self.label_8.setGeometry(QtCore.QRect(110, 170, 51, 16))
self.label_8.setObjectName(_fromUtf8("label_8"))
self.label_9 = QtGui.QLabel(Dialog)
self.label_9.setGeometry(QtCore.QRect(190, 380, 46, 13))
self.label_9.setObjectName(_fromUtf8("label_9"))
self.retranslateUi(Dialog)
QtCore.QMetaObject.connectSlotsByName(Dialog)
def retranslateUi(self, Dialog):
Dialog.setWindowTitle(_translate("Dialog", "Dialog", None))
self.label.setText(_translate("Dialog", "Birthday Calendar", None))
self.dateEdit.setDisplayFormat(_translate("Dialog", "d/m/yyyy", None))
self.dateEdit_2.setDisplayFormat(_translate("Dialog", "d/m/yyyy", None))
self.label_2.setText(_translate("Dialog", "2019 Calendar", None))
self.label_3.setText(_translate("Dialog", "Marelize Jansen van Vuuren", None))
self.label_4.setText(_translate("Dialog", "Student no: 60858753", None))
self.pushButton.setText(_translate("Dialog", "Calculate Age", None))
self.label_5.setText(_translate("Dialog", "Select DOB and Calculate exact age", None))
self.label_6.setText(_translate("Dialog", "Current Age", None))
self.label_7.setText(_translate("Dialog", "Select today\'s date", None))
self.label_8.setText(_translate("Dialog", "D/MM/YYY", None))
self.label_9.setText(_translate("Dialog", "D/MM/YY", None))
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
Dialog = QtGui.QDialog()
ui = Ui_Dialog()
ui.setupUi(Dialog)
Dialog.show()
sys.exit(app.exec_())
This is the code to invoke and display the user interface
import sys
from dispcalendar import*
class MyForm(QtGui.QDialog):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.ui = Ui_Dialog()
self.ui.setupUi(self)
QtCore.QObject.connect(self.ui.calendarWidget, QtCore.SIGNAL('selectionChanged()'), self.dispdate)
QtCore.QObject.connect(self.ui.calendarWidget_2, QtCore.SIGNAL('selectionChanged()'), self.dispdate)
self.dispdate()
def dispdate(self):
self.ui.dateEdit_2.setDate(self.ui.calendarWidget.selectedDate())
self.ui.dateEdit.setDate(self.ui.calendarWidget_2.selectedDate())
self.ui.dateEdit_2.display(text)
self.ui.dateEdit.display(text)
self.ui.calendarWidget.display(text)
self.ui.calendarWidget_2.display(text)
if __name__=="__main__":
app = QtGui.QApplication(sys.argv)
myapp = MyForm()
myapp.show()
sys.exit(app.exec_())
As the title says, my plot does not update. The objetive is to initiate the plot when the button is clicked. The window pops up and the axis are formed, but no curve is plotted. i used pyqt5 in qt designer fr the GUI and pyqtgraph for the plot. if i wanted to add more plots in the same window whats the optimal way to do it. Thanks
Code:
from PyQt5 import QtCore, QtGui, QtWidgets
import os,serial,jeje_rc
os.environ["TF_CPP_MIN_LOG_LEVEL"]="3"
import numpy as np
import pyqtgraph as pg
class Ui_MainWindow(object):
def ser(self):
self.raw = serial.Serial('COM4', 9600)
self.raw.close()
self.raw.open()
def update(self):
self.datos = self.raw.readline()
self.datos1 = self.datos.decode().split(',')
self.y1[self.m] = self.datos1[0]
if self.m == 99:
self.y1 = np.zeros(100, dtype=float)
self.m = 0
else:
self.m += 1
self.curva1.setData(self.y1)
app.processEvents()
def start(self):
self.ser()
self.win = pg.GraphicsWindow()
self.win.setWindowTitle('Datos de arduino')
self.p1 = self.win.addPlot()
self.p1.setYRange(0, 1024, padding=0)
self.curva1 = self.p1.plot()
self.datos = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
self.y1 = np.zeros(100, dtype=float)
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.setWindowTitle("ECG de 12 Derivaciones UAO")
MainWindow.resize(800, 550)
self.m=0
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setMaximumSize(QtCore.QSize(805, 510))
self.centralwidget.setObjectName("centralwidget")
self.centralwidget.setWindowTitle("ECG de 12 Derivaciones UAO")
self.label = QtWidgets.QLabel(self.centralwidget)
self.label.setGeometry(QtCore.QRect(20, 270, 241, 19))
self.label.setObjectName("label")
self.line = QtWidgets.QFrame(self.centralwidget)
self.line.setGeometry(QtCore.QRect(10, 230, 781, 20))
self.line.setFrameShape(QtWidgets.QFrame.HLine)
self.line.setFrameShadow(QtWidgets.QFrame.Sunken)
self.line.setObjectName("line")
self.label_2 = QtWidgets.QLabel(self.centralwidget)
self.label_2.setGeometry(QtCore.QRect(600, 40, 181, 171))
self.label_2.setObjectName("label_2")
self.label_3 = QtWidgets.QLabel(self.centralwidget)
self.label_3.setGeometry(QtCore.QRect(40, 10, 591, 41))
font = QtGui.QFont()
font.setPointSize(16)
self.label_3.setFont(font)
self.label_3.setObjectName("label_3")
self.label_4 = QtWidgets.QLabel(self.centralwidget)
self.label_4.setGeometry(QtCore.QRect(170, 150, 221, 41))
font = QtGui.QFont()
font.setPointSize(11)
self.label_4.setFont(font)
self.label_4.setObjectName("label_4")
self.label_5 = QtWidgets.QLabel(self.centralwidget)
self.label_5.setGeometry(QtCore.QRect(110, 190, 471, 41))
font = QtGui.QFont()
font.setPointSize(11)
self.label_5.setFont(font)
self.label_5.setObjectName("label_5")
self.label_6 = QtWidgets.QLabel(self.centralwidget)
self.label_6.setGeometry(QtCore.QRect(50, 100, 521, 51))
font = QtGui.QFont()
font.setPointSize(9)
self.label_6.setFont(font)
self.label_6.setObjectName("label_6")
self.lineEdad = QtWidgets.QLineEdit(self.centralwidget)
self.lineEdad.setGeometry(QtCore.QRect(110, 310, 261, 21))
self.lineEdad.setObjectName("lineEdad")
self.lineNombre = QtWidgets.QLineEdit(self.centralwidget)
self.lineNombre.setGeometry(QtCore.QRect(110, 270, 261, 20))
self.lineNombre.setObjectName("lineNombre")
self.BotonInicio = QtWidgets.QPushButton(self.centralwidget)
self.BotonInicio.setGeometry(QtCore.QRect(490, 290, 181, 41))
self.BotonInicio.setObjectName("BotonInicio")
self.BotonInicio.clicked.connect(self.start)
self.label_7 = QtWidgets.QLabel(self.centralwidget)
self.label_7.setGeometry(QtCore.QRect(20, 310, 68, 19))
self.label_7.setObjectName("label_7")
self.label_8 = QtWidgets.QLabel(self.centralwidget)
self.label_8.setGeometry(QtCore.QRect(20, 350, 61, 19))
self.label_8.setObjectName("label_8")
self.label_9 = QtWidgets.QLabel(self.centralwidget)
self.label_9.setGeometry(QtCore.QRect(20, 380, 111, 31))
self.label_9.setObjectName("label_9")
self.BoxGenero = QtWidgets.QComboBox(self.centralwidget)
self.BoxGenero.setGeometry(QtCore.QRect(110, 350, 92, 25))
self.BoxGenero.setObjectName("BoxGenero")
self.BoxGenero.addItem("")
self.BoxGenero.addItem("")
self.plainTextPatologias = QtWidgets.QPlainTextEdit(self.centralwidget)
self.plainTextPatologias.setGeometry(QtCore.QRect(110, 390, 261, 91))
self.plainTextPatologias.setObjectName("plainTextPatologias")
self.line_2 = QtWidgets.QFrame(self.centralwidget)
self.line_2.setGeometry(QtCore.QRect(390, 250, 20, 241))
self.line_2.setFrameShape(QtWidgets.QFrame.VLine)
self.line_2.setFrameShadow(QtWidgets.QFrame.Sunken)
self.line_2.setObjectName("line_2")
self.BotonExportar = QtWidgets.QPushButton(self.centralwidget)
self.BotonExportar.setGeometry(QtCore.QRect(490, 410, 181, 41))
self.BotonExportar.setObjectName("BotonExportar")
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 805, 31))
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)
timer = QtCore.QTimer()
timer.timeout.connect(self.update)
timer.start(0)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "ECG de 12 Derivaciones"))
self.label.setText(_translate("MainWindow", "Nombre:"))
self.label_2.setText(_translate("MainWindow", "<html><head/><body><p><img src=\":/newPrefix/logo-universidad-autonoma-de-occidente.png\"/></p></body></html>"))
self.label_3.setText(_translate("MainWindow", "Electrocardiógrafo De 12 Derivaciones"))
self.label_4.setText(_translate("MainWindow", "Facultad de ingenieria"))
self.label_5.setText(_translate("MainWindow", " Universidad Autonoma De Occidente"))
self.label_6.setText(_translate("MainWindow", "Por: Mario Gomez, Viviana Calero, Sara Chillito, Stefania Calderon"))
self.BotonInicio.setText(_translate("MainWindow", "Inicio del programa"))
self.label_7.setText(_translate("MainWindow", "Edad:"))
self.label_8.setText(_translate("MainWindow", "Genero:"))
self.label_9.setText(_translate("MainWindow", "Patologias:"))
self.BoxGenero.setItemText(0, _translate("MainWindow", "Hombre"))
self.BoxGenero.setItemText(1, _translate("MainWindow", "Mujer"))
self.BotonExportar.setText(_translate("MainWindow", "Exportar datos"))
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_())
It is recommended not to modify the code provided by Qt Designer since if you want to modify the design you will have to rewrite your code, besides the Ui_MainWindow class is not a widget but a class that is used to fill some widget, so I recommend deleting the changes .
On the other hand is not suitable to run with a timer with a range of 0, since it does not allow updating the GUI, on the other hand the reading of the serial is blocking, so a possible solution is to use QThread, and use a signal to update the data in the GUI thread.
class Ui_MainWindow(object):
...
class ArduinoThread(QtCore.QThread):
dataChanged = QtCore.pyqtSignal(str)
def __init__(self, *args, **kwargs):
QtCore.QThread.__init__(self, *args, **kwargs)
self.raw = serial.Serial('com4', 9600)
self.raw.close()
self.raw.open()
def run(self):
while True:
datos_array = self.raw.readline().decode().split(',')
if datos_array:
datos = datos_array[0]
self.dataChanged.emit(datos)
QtCore.QThread.msleep(10)
class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
def __init__(self, *args, **kwargs):
QtWidgets.QMainWindow.__init__(self, *args, **kwargs)
self.setupUi(self)
self.BotonInicio.clicked.connect(self.start)
self.m = 0
def update_plot(self, dato):
if self.m > 99:
self.y1 = np.zeros(100, dtype=float)
self.m = 0
else:
self.y1[self.m] = dato
self.m += 1
self.curva1.setData(self.y1)
def start(self):
thread = ArduinoThread(self)
thread.dataChanged.connect(self.update_plot)
thread.start()
self.win = pg.GraphicsWindow()
self.win.setWindowTitle('Datos de arduino')
self.p1 = self.win.addPlot()
self.p1.setYRange(0, 1024, padding=0)
self.curva1 = self.p1.plot()
self.y1 = np.zeros(100, dtype=float)
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
w = MainWindow()
w.show()
sys.exit(app.exec_())
As you can see, I have made some changes to improve the application as verifications, use variables when necessary, etc.
Although a way compatible with Qt is to use QSerialPort that emits the readyRead signal when there is a new data:
from PyQt5 import QtCore, QtGui, QtWidgets, QtSerialPort
....
class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
def __init__(self, *args, **kwargs):
QtWidgets.QMainWindow.__init__(self, *args, **kwargs)
self.setupUi(self)
self.BotonInicio.clicked.connect(self.start)
def update_plot(self):
while self.ser.canReadLine():
line = bytearray(self.ser.readLine()).decode()
self.processLine(line)
def processLine(self, line):
datos_array = line.strip().split(',')
if datos_array:
dato = datos_array[0]
if self.m > 99:
self.y1 = np.zeros(100, dtype=float)
self.m = 0
else:
self.y1[self.m] = dato
self.m += 1
self.curva1.setData(self.y1)
def start(self):
self.ser = QtSerialPort.QSerialPort("com4", self)
self.ser.setBaudRate(9600)
self.ser.readyRead.connect(self.update_plot)
self.ser.open(QtSerialPort.QSerialPort.ReadOnly)
self.win = pg.GraphicsWindow()
self.win.setWindowTitle('Datos de arduino')
self.p1 = self.win.addPlot()
self.p1.setYRange(0, 1024, padding=0)
self.curva1 = self.p1.plot()
self.y1 = np.zeros(100, dtype=float)
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
w = MainWindow()
w.show()
sys.exit(app.exec_())
I create GUI Design in Qt4 and you can see the Design here.
Than, with pyuic4 i converted design into GuiVezba2DialogQt4.py.
Here you can see a Code for that class:
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
try:
_encoding = QtGui.QApplication.UnicodeUTF8
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig
class Ui_Dialog(object):
def setupUi(self, Dialog):
Dialog.setObjectName(_fromUtf8("Dialog"))
Dialog.resize(554, 407)
self.horizontalLayoutWidget = QtGui.QWidget(Dialog)
self.horizontalLayoutWidget.setGeometry(QtCore.QRect(40, 10, 411, 61))
self.horizontalLayoutWidget.setObjectName(_fromUtf8("horizontalLayoutWidget"))
self.horizontalLayout = QtGui.QHBoxLayout(self.horizontalLayoutWidget)
self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout"))
self.pushButton = QtGui.QPushButton(self.horizontalLayoutWidget)
self.pushButton.setObjectName(_fromUtf8("pushButton"))
self.horizontalLayout.addWidget(self.pushButton)
self.pushButton_2 = QtGui.QPushButton(self.horizontalLayoutWidget)
self.pushButton_2.setObjectName(_fromUtf8("pushButton_2"))
self.horizontalLayout.addWidget(self.pushButton_2)
self.pushButton_3 = QtGui.QPushButton(self.horizontalLayoutWidget)
self.pushButton_3.setObjectName(_fromUtf8("pushButton_3"))
self.horizontalLayout.addWidget(self.pushButton_3)
self.horizontalLayoutWidget_2 = QtGui.QWidget(Dialog)
self.horizontalLayoutWidget_2.setGeometry(QtCore.QRect(40, 70, 411, 41))
self.horizontalLayoutWidget_2.setObjectName(_fromUtf8("horizontalLayoutWidget_2"))
self.horizontalLayout_2 = QtGui.QHBoxLayout(self.horizontalLayoutWidget_2)
self.horizontalLayout_2.setObjectName(_fromUtf8("horizontalLayout_2"))
self.label_20 = QtGui.QLabel(self.horizontalLayoutWidget_2)
self.label_20.setObjectName(_fromUtf8("label_20"))
self.horizontalLayout_2.addWidget(self.label_20)
self.label_21 = QtGui.QLabel(self.horizontalLayoutWidget_2)
self.label_21.setObjectName(_fromUtf8("label_21"))
self.horizontalLayout_2.addWidget(self.label_21)
self.label_22 = QtGui.QLabel(self.horizontalLayoutWidget_2)
self.label_22.setObjectName(_fromUtf8("label_22"))
self.horizontalLayout_2.addWidget(self.label_22)
self.groupBox = QtGui.QGroupBox(Dialog)
self.groupBox.setGeometry(QtCore.QRect(10, 130, 291, 171))
self.groupBox.setObjectName(_fromUtf8("groupBox"))
self.label = QtGui.QLabel(self.groupBox)
self.label.setGeometry(QtCore.QRect(10, 20, 91, 21))
self.label.setObjectName(_fromUtf8("label"))
self.lineEdit = QtGui.QLineEdit(self.groupBox)
self.lineEdit.setGeometry(QtCore.QRect(170, 20, 51, 20))
self.lineEdit.setObjectName(_fromUtf8("lineEdit"))
self.pushButton_4 = QtGui.QPushButton(self.groupBox)
self.pushButton_4.setGeometry(QtCore.QRect(160, 130, 75, 23))
self.pushButton_4.setObjectName(_fromUtf8("pushButton_4"))
self.label_4 = QtGui.QLabel(self.groupBox)
self.label_4.setGeometry(QtCore.QRect(170, 70, 111, 16))
self.label_4.setObjectName(_fromUtf8("label_4"))
self.label_9 = QtGui.QLabel(self.groupBox)
self.label_9.setGeometry(QtCore.QRect(170, 110, 111, 16))
self.label_9.setObjectName(_fromUtf8("label_9"))
self.label_3 = QtGui.QLabel(self.groupBox)
self.label_3.setGeometry(QtCore.QRect(170, 50, 111, 16))
self.label_3.setObjectName(_fromUtf8("label_3"))
self.label_5 = QtGui.QLabel(self.groupBox)
self.label_5.setGeometry(QtCore.QRect(170, 90, 111, 16))
self.label_5.setObjectName(_fromUtf8("label_5"))
self.label_2 = QtGui.QLabel(self.groupBox)
self.label_2.setGeometry(QtCore.QRect(10, 50, 131, 16))
self.label_2.setObjectName(_fromUtf8("label_2"))
self.label_12 = QtGui.QLabel(self.groupBox)
self.label_12.setGeometry(QtCore.QRect(10, 70, 131, 16))
self.label_12.setObjectName(_fromUtf8("label_12"))
self.label_13 = QtGui.QLabel(self.groupBox)
self.label_13.setGeometry(QtCore.QRect(10, 90, 131, 16))
self.label_13.setObjectName(_fromUtf8("label_13"))
self.label_14 = QtGui.QLabel(self.groupBox)
self.label_14.setGeometry(QtCore.QRect(10, 110, 131, 16))
self.label_14.setObjectName(_fromUtf8("label_14"))
self.label_15 = QtGui.QLabel(self.groupBox)
self.label_15.setGeometry(QtCore.QRect(10, 130, 131, 16))
self.label_15.setObjectName(_fromUtf8("label_15"))
self.groupBox_2 = QtGui.QGroupBox(Dialog)
self.groupBox_2.setGeometry(QtCore.QRect(310, 130, 241, 171))
self.groupBox_2.setObjectName(_fromUtf8("groupBox_2"))
self.label_10 = QtGui.QLabel(self.groupBox_2)
self.label_10.setGeometry(QtCore.QRect(10, 30, 71, 16))
self.label_10.setObjectName(_fromUtf8("label_10"))
self.lineEdit_2 = QtGui.QLineEdit(self.groupBox_2)
self.lineEdit_2.setGeometry(QtCore.QRect(140, 30, 71, 20))
self.lineEdit_2.setInputMask(_fromUtf8(""))
self.lineEdit_2.setText(_fromUtf8(""))
self.lineEdit_2.setObjectName(_fromUtf8("lineEdit_2"))
self.label_6 = QtGui.QLabel(self.groupBox_2)
self.label_6.setGeometry(QtCore.QRect(140, 60, 61, 16))
self.label_6.setObjectName(_fromUtf8("label_6"))
self.label_7 = QtGui.QLabel(self.groupBox_2)
self.label_7.setGeometry(QtCore.QRect(140, 80, 71, 16))
self.label_7.setObjectName(_fromUtf8("label_7"))
self.label_8 = QtGui.QLabel(self.groupBox_2)
self.label_8.setGeometry(QtCore.QRect(140, 100, 71, 16))
self.label_8.setObjectName(_fromUtf8("label_8"))
self.label_11 = QtGui.QLabel(self.groupBox_2)
self.label_11.setGeometry(QtCore.QRect(140, 120, 71, 16))
self.label_11.setObjectName(_fromUtf8("label_11"))
self.pushButton_5 = QtGui.QPushButton(self.groupBox_2)
self.pushButton_5.setGeometry(QtCore.QRect(130, 140, 75, 23))
self.pushButton_5.setObjectName(_fromUtf8("pushButton_5"))
self.label_19 = QtGui.QLabel(self.groupBox_2)
self.label_19.setGeometry(QtCore.QRect(0, 80, 121, 16))
self.label_19.setObjectName(_fromUtf8("label_19"))
self.label_18 = QtGui.QLabel(self.groupBox_2)
self.label_18.setGeometry(QtCore.QRect(0, 60, 131, 16))
self.label_18.setObjectName(_fromUtf8("label_18"))
self.label_17 = QtGui.QLabel(self.groupBox_2)
self.label_17.setGeometry(QtCore.QRect(0, 100, 131, 16))
self.label_17.setObjectName(_fromUtf8("label_17"))
self.label_16 = QtGui.QLabel(self.groupBox_2)
self.label_16.setGeometry(QtCore.QRect(0, 120, 131, 16))
self.label_16.setObjectName(_fromUtf8("label_16"))
self.retranslateUi(Dialog)
QtCore.QMetaObject.connectSlotsByName(Dialog)
def retranslateUi(self, Dialog):
Dialog.setWindowTitle(_translate("Dialog", "Dialog", None))
self.pushButton.setText(_translate("Dialog", "Button1", None))
self.pushButton_2.setText(_translate("Dialog", "Button2", None))
self.pushButton_3.setText(_translate("Dialog", "Button3", None))
self.label_20.setText(_translate("Dialog", "Konektuj se na bazu", None))
self.label_21.setText(_translate("Dialog", "Ucitaj Detaljne Tacke", None))
self.label_22.setText(_translate("Dialog", "Ucitaj Parcele", None))
self.groupBox.setTitle(_translate("Dialog", "GroupBox1", None))
self.label.setText(_translate("Dialog", "Oznaka Parcele:", None))
self.pushButton_4.setText(_translate("Dialog", "Button4", None))
self.label_4.setText(_translate("Dialog", "label4", None))
self.label_9.setText(_translate("Dialog", "label9", None))
self.label_3.setText(_translate("Dialog", "label3", None))
self.label_5.setText(_translate("Dialog", "label5", None))
self.label_2.setText(_translate("Dialog", "Povrsina parcele je:", None))
self.label_12.setText(_translate("Dialog", "Broj Prelomnih Tacaka je:", None))
self.label_13.setText(_translate("Dialog", "Nacin koriscenja je:", None))
self.label_14.setText(_translate("Dialog", "WKT format geometrije je:", None))
self.label_15.setText(_translate("Dialog", "Ucitaj podatke:", None))
self.groupBox_2.setTitle(_translate("Dialog", "GroupBox2", None))
self.label_10.setText(_translate("Dialog", "Broj Tacke", None))
self.label_6.setText(_translate("Dialog", "label6", None))
self.label_7.setText(_translate("Dialog", "label7", None))
self.label_8.setText(_translate("Dialog", "label8", None))
self.label_11.setText(_translate("Dialog", "label11", None))
self.pushButton_5.setText(_translate("Dialog", "Button5", None))
self.label_19.setText(_translate("Dialog", "Koordinata Y je:", None))
self.label_18.setText(_translate("Dialog", "Koordinata X je:", None))
self.label_17.setText(_translate("Dialog", "Da li ucestvuje u parceli:", None))
self.label_16.setText(_translate("Dialog", "WKT oblik Geometrije", None))
Than in my main python file - Vezba2.py I have this:
import pypyodbc
import DetaljnaTacka
import Poligon
import Parcela
from GuiVezba2DialogQt4 import *
import sys
class MyForm(QtGui.QDialog):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.ui = Ui_Dialog()
self.ui.setupUi(self)
QtCore.QObject.connect(self.ui.pushButton_4, QtCore.SIGNAL('clicked()'),self.
dispmessage)
def dispmessage(self):
self.ui.label_10.setText("Hello ")
if __name__ == "__main__":
app = QtGui.QGuiApplication(sys.argv)
myapp = MyForm()
myapp.show()
sys.exit(app.exec_())
When i Run program, with debagger i put Break point at myapp=MyForm(). When that step try to execute, program is over. I don't see created GUI and i dont see any error.
What should i do please?
Thank you.
I made i mistake. I typed:
app = QtGui.QGuiApplication instead app = QtGui.QApplication