I used this code to manage a countdown using PyQt5. code -
import time
import serial
from PyQt5 import QtCore
argument = serial.Serial('COM5',9600)
countDown = 9999
def timerEvent():
global time
time = time.addSecs(-1)
global argument
global new
data = time.toString("mmss")
print(data)
argument.write(data.encode());
if data == '0000':
argument.close()
timer.stop()
global countDown
countDown = data
time.sleep(2);
app = QtCore.QCoreApplication(sys.argv)
timer = QtCore.QTimer()
time = QtCore.QTime(0, 1,0)
timer.timeout.connect(timerEvent)
timer.start(200)
But i want is i will input the minute and increment value using a GUI.But, can not implement. Any suggestions how can i implement that?
heres my GUI
I created a new self function under class Ui_Mainwindow that connects the button to implement timer. However, it always says self error. i know how to get the lineEdit values but when i want to put it in
line 38 time = QtCore.QTime(0, 1,0) it shows self error. again the line no 40 timer.timeout.connect(timerEvent) timerevent shows error.
any idea how to implement using the GUI ? Sorry for my poor explanation. is there any other way to do this?
heres the code, i just tried to do similar like base code mentioned above.
import time
countDown = 9999
from PyQt5 import QtCore, QtGui, QtWidgets
inc = 9999
newTime = 9999
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.groupBox = QtWidgets.QGroupBox(self.centralwidget)
self.groupBox.setGeometry(QtCore.QRect(70, 180, 131, 121))
self.groupBox.setTitle("")
self.groupBox.setObjectName("groupBox")
self.label_2 = QtWidgets.QLabel(self.groupBox)
self.label_2.setGeometry(QtCore.QRect(6, 50, 51, 20))
self.label_2.setObjectName("label_2")
self.lineEdit_Time = QtWidgets.QLineEdit(self.groupBox)
self.lineEdit_Time.setGeometry(QtCore.QRect(60, 20, 61, 20))
self.lineEdit_Time.setObjectName("lineEdit_Time")
self.lineEdit_Increment = QtWidgets.QLineEdit(self.groupBox)
self.lineEdit_Increment.setGeometry(QtCore.QRect(60, 50, 61, 20))
self.lineEdit_Increment.setObjectName("lineEdit_Increment")
self.pushButton_Start = QtWidgets.QPushButton(self.groupBox)
self.pushButton_Start.setGeometry(QtCore.QRect(10, 90, 111, 23))
self.pushButton_Start.setObjectName("pushButton_Start")
self.label = QtWidgets.QLabel(self.groupBox)
self.label.setGeometry(QtCore.QRect(10, 20, 47, 13))
self.label.setObjectName("label")
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 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)
self.pushButton_Start.clicked.connect(self.update)
global inc
inc = self.lineEdit_Time.text()
global newTime
newTime = self.lineEdit_Increment.text()
def update(self):
global time
time = time.addSecs(-1)
global argument
global new
data = time.toString("mmss")
print(data)
argument.write(data.encode());
if data == '0000':
timer.stop()
global countDown
countDown = data
return time
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.label_2.setText(_translate("MainWindow", "Increment"))
self.pushButton_Start.setText(_translate("MainWindow", "START"))
self.label.setText(_translate("MainWindow", "Time"))
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
global time
timer = QtCore.QTimer()
time = QtCore.QTime(0, inc,0)
timer.timeout.connect(update)
timer.start(newTime)
MainWindow.show()
sys.exit(app.exec_())
Something like this? You want to access your increment and start time from the text values of the self.lineEdit_Time and self.lineEdit_Increment widgets. Then you use this in a start_timer method, which you connect to the start buttons clicked signal.
In the start_timer method, we create a timer which is a member of the main_window object,
and this timer's timeout signal is connected to our update_clock method, which updates the countdown based on the self.increment value.
class Ui_MainWindow(object):
#...
self.pushButton_Start.pressed.connect(self.start_timer)
def start_timer(self):
self.countdown = int(self.lineEdit_Time.text())
self.increment = int(self.lineEdit_Increment.text())
self.countdownTimer = QtCore.QTimer()
self.countdownTimer.timeout.connect(self.update_clock)
self.countdownTimer.start(1000) # fires every 1000ms = 1s
def update_clock(self):
self.countdown -= self.increment
#update a clock label that shows the countdown value
self.clockLabel.setText(self.countdown)
#or just print the vaule for now
print(self.countdown)
Related
Below are the 2 window codes, 1st is main window and 2nd is widget window:
from Open import Ui_Form
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def open(self):
self.window = QtWidgets.QWidget()
self.ui = Ui_Form()
self.ui.setupUi(self.window)
self.window.show()
def get_result(self):
answer = []
Unsqueeze_result = set(answer)
final = list(Unsqueeze_result)
final.sort()
self.final_list = [x.upper() for x in final]
self.listView.addItems(self.final_list)
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(800, 600)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.listView = QtWidgets.QListView(self.centralwidget)
self.listView.setGeometry(QtCore.QRect(270, 140, 256, 371))
self.listView.setObjectName("listView")
self.result_button = QtWidgets.QPushButton(self.centralwidget)
self.result_button.setGeometry(QtCore.QRect(350, 70, 91, 41))
self.result_button.setObjectName("result_button")
self.result_button.pressed.connect(self.get_result)
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 21))
self.menubar.setObjectName("menubar")
self.menuFile = QtWidgets.QMenu(self.menubar)
self.menuFile.setObjectName("menuFile")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.actionOpen = QtWidgets.QAction(MainWindow)
self.actionOpen.setObjectName("actionOpen")
self.actionOpen.triggered.connect(lambda:self.open())
self.menuFile.addAction(self.actionOpen)
self.menubar.addAction(self.menuFile.menuAction())
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.result_button.setText(_translate("MainWindow", "Result"))
self.menuFile.setTitle(_translate("MainWindow", "File"))
self.actionOpen.setText(_translate("MainWindow", "Open"))
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_())
Below are 2nd window:
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Form(object):
def __init__(self):
self.list_result = []
def setupUi(self, Form):
Form.setObjectName("Form")
Form.resize(400, 300)
self.checkBox_1 = QtWidgets.QCheckBox(Form)
self.checkBox_1.setGeometry(QtCore.QRect(60, 70, 121, 31))
self.checkBox_1.setObjectName("checkBox_1")
self.checkBox_2 = QtWidgets.QCheckBox(Form)
self.checkBox_2.setGeometry(QtCore.QRect(60, 110, 111, 31))
self.checkBox_2.setObjectName("checkBox_2")
self.pushButton_ok = QtWidgets.QPushButton(Form)
self.pushButton_ok.setGeometry(QtCore.QRect(90, 200, 71, 31))
self.pushButton_ok.setObjectName("pushButton")
self.pushButton_ok.pressed.connect(self.OK_thread)
self.pushButton_cancel = QtWidgets.QPushButton(Form)
self.pushButton_cancel.setGeometry(QtCore.QRect(210, 200, 71, 31))
self.pushButton_cancel.setObjectName("pushButton_2")
self.pushButton_cancel.clicked.connect(Form.close)
self.retranslateUi(Form)
QtCore.QMetaObject.connectSlotsByName(Form)
def retranslateUi(self, Form):
_translate = QtCore.QCoreApplication.translate
Form.setWindowTitle(_translate("Form", "Form"))
self.checkBox_1.setText(_translate("Form", "Test1"))
self.checkBox_2.setText(_translate("Form", "Test 2"))
self.pushButton.setText(_translate("Form", "OK"))
self.pushButton_2.setText(_translate("Form", "Cancel"))
def OK_thread(self):
global submit_execute_thread
self.pushButton_ok.setEnabled(False)
self.pushButton_cancel.setEnabled(False)
submit_execute_thread = QThread()
submit_execute_thread.started.connect(self.ok_execute)
submit_execute_thread.start()
self.check_execute_thread()
def check_execute_thread(self):
if submit_execute_thread.isRunning() == True:
time.sleep(10)
self.check_execute_thread()
else:
Form.close()
def ok_execute(self):
if self.checkBox_1.isChecked() and self.checkBox_2.ischecked():
self.list_result = ["a","b","c","d","e"]
i have 2 issue here:
My objective is click the File --> Open and 2nd window appear, when i tick the checkbox1 and checkbox2 and press ok_button, i connect the ok_button to OK_thread and make a Qthread to ok_execute function to prevent freezing while running the function and keep checking the thread every 10 seconds until it run finish and close the Form window. I am not sure what is the issue here as it could not work, my GUI still freezing after i press OK_button and never run finish.
passing value:
i try to define the list = [] in def init() in both main window and 2nd window but some variable become not declarable such as "Form", so when i open the Form window from main window, it could not work. and another issue is how do i pass the value from Form window which is from ok_execute return self.list_result to Mainwindow, so when i click the result button in Main Window, it will show the list_result in the listview widget.
Please help me modify the code and appreciate your help.
Thank you.
Regards,
cstung89
I'm trying to get an output from an arduino to be updated in two pyqt windows, one of which is a matplotlib plot. If I comment out the non-plot thread window, the plot works. But when I try to run both at the same time, I get the message
3 Device is already open
3 Device is already open
but nothing shows up in the plot, though the window is there. Whereas the non-plot window is updated with values. I'm not sure if I should use QThreadpool instead of QThread. On a side note, if I try to rerun the code, I get the message
2 Access is denied.
2 Access is denied.
2 Access is denied.
so I have to unplug and replug in the arduino, uploading its code again, before running the python script again, and neither window is updated with values.
The arduino code I use, to just give signals over 1 second intervals, to test it out, is
int PinOutput = 13;
int PinInput = A0;
int inph;
int inpl;
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
pinMode(PinInput, INPUT);
pinMode(PinOutput, OUTPUT);
}
void loop() {
// put your main code here, to run repeatedly:
inpl = analogRead(PinInput)/4;
Serial.println(inpl);
analogWrite(PinOutput,255);
delay(1000);
inph = analogRead(PinInput)/4;
Serial.println(inph);
analogWrite(PinOutput,0);
delay(1000);
}
Where pin 13 is connected to A0 on the arduino.
The python code is
import sys
from PyQt5 import QtCore, QtWidgets, QtSerialPort
from matplotlib.figure import Figure
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg
seril_port_connection = QtSerialPort.QSerialPort("COM3")
seril_port_connection.setBaudRate(QtSerialPort.QSerialPort.Baud9600)
class MyThread2(QtCore.QThread):
ard_signal = QtCore.pyqtSignal(str)
def __init__(self):
QtCore.QThread.__init__(self)
self.serial_port = seril_port_connection
self.serial_port.errorOccurred.connect(self.handle_error)
self.serial_port.readyRead.connect(self.run)
self.serial_port.open(QtCore.QIODevice.ReadWrite)
def run(self):
while self.serial_port.canReadLine():
line = self.serial_port.readLine().data().decode().strip().strip('\x00')
try:
self.ard_signal.emit(str(line))
except ValueError as e:
print("error", e)
def handle_error(self, error):
if error == QtSerialPort.QSerialPort.NoError:
return
print(error, self.serial_port.errorString())
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(325, 237)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.label = QtWidgets.QLabel(self.centralwidget)
self.label.setGeometry(QtCore.QRect(110, 20, 61, 16))
self.label.setObjectName("label")
self.textEdit = QtWidgets.QTextEdit(self.centralwidget)
self.textEdit.setGeometry(QtCore.QRect(90, 60, 104, 71))
self.textEdit.setObjectName("textEdit")
self.pushButton = QtWidgets.QPushButton(self.centralwidget)
self.pushButton.setGeometry(QtCore.QRect(100, 150, 75, 23))
self.pushButton.setObjectName("pushButton")
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 325, 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 retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "test window"))
self.label.setText(_translate("MainWindow", "pyqt5 tests"))
self.pushButton.setText(_translate("MainWindow", "test button"))
self.pushButton.clicked.connect(self.label_change)
self.thread_start = MyThread()
self.thread_start.ard_signal.connect(self.label.setText)
self.thread_start.start()
def label_change(self):
self.pushButton.setText('Button Clicked!')
self.textEdit.setText('taco')
class MainWindowm(QtWidgets.QMainWindow):
def __init__(self, *args, **kwargs):
super(MainWindowm, self).__init__(*args, **kwargs)
self.canvas = FigureCanvasQTAgg(Figure(figsize=(5, 4), dpi=100))
self.setCentralWidget(self.canvas)
self.axes = self.canvas.figure.subplots()
n_data = 10
self.xdata = list(range(n_data))
self.ydata = [0 for i in range(n_data)]
self.thread_start = MyThread2()
self.thread_start.ard_signal.connect(self.update_plot)
self.thread_start.start()
def handle_error(self, error):
if error == QtSerialPort.QSerialPort.NoError:
return
print(error, self.serial_port.errorString())
def update_plot(self, value):
self.ydata = self.ydata[1:] + [float(value)]
self.axes.cla()
self.axes.plot(self.xdata, self.ydata, "r")
self.canvas.draw()
class MyThread(QtCore.QThread):
ard_signal = QtCore.pyqtSignal(str)
def __init__(self):
QtCore.QThread.__init__(self)
self.serial_port = seril_port_connection
self.serial_port.errorOccurred.connect(self.handle_error)
self.serial_port.readyRead.connect(self.run)
self.serial_port.open(QtCore.QIODevice.ReadWrite)
def run(self):
while self.serial_port.canReadLine():
line = self.serial_port.readLine().data().decode().strip().strip('\x00')
try:
self.ard_signal.emit(str(line))
except ValueError as e:
print("error", e)
def handle_error(self, error):
if error == QtSerialPort.QSerialPort.NoError:
return
print(error, self.serial_port.errorString())
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
w = MainWindowm()
w.show()
sys.exit(app.exec_())
So I'm trying to make the arduino output available globally, to then be used by different threads at the same time, being updated in two windows, one with a plot. Any info on how to do this would help, thanks.
I assume that the OP is using my old answer, and in that solution indicate that the use of QSerialPort avoids the unnecessary use of threads, and this also applies in this case. On the other hand, a serial port cannot be handled by several classes. In this case, you just have to create a class that manages the serial port and distributes the information to the other elements.
import sys
from PyQt5 import QtCore, QtWidgets, QtSerialPort
from matplotlib.figure import Figure
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(325, 237)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.label = QtWidgets.QLabel(self.centralwidget)
self.label.setGeometry(QtCore.QRect(110, 20, 61, 16))
self.label.setObjectName("label")
self.textEdit = QtWidgets.QTextEdit(self.centralwidget)
self.textEdit.setGeometry(QtCore.QRect(90, 60, 104, 71))
self.textEdit.setObjectName("textEdit")
self.pushButton = QtWidgets.QPushButton(self.centralwidget)
self.pushButton.setGeometry(QtCore.QRect(100, 150, 75, 23))
self.pushButton.setObjectName("pushButton")
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 325, 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 retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "test window"))
self.label.setText(_translate("MainWindow", "pyqt5 tests"))
self.pushButton.setText(_translate("MainWindow", "test button"))
class MainWindowm(QtWidgets.QMainWindow):
def __init__(self, *args, **kwargs):
super(MainWindowm, self).__init__(*args, **kwargs)
self.canvas = FigureCanvasQTAgg(Figure(figsize=(5, 4), dpi=100))
self.setCentralWidget(self.canvas)
self.axes = self.canvas.figure.subplots()
n_data = 10
self.xdata = list(range(n_data))
self.ydata = [0 for i in range(n_data)]
def update_plot(self, value):
self.ydata = self.ydata[1:] + [value]
self.axes.cla()
self.axes.plot(self.xdata, self.ydata, "r")
self.canvas.draw()
class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
def __init__(self, parent=None):
super().__init__(parent)
self.setupUi(self)
def update_text(self, value):
self.label.setNum(value)
self.label.adjustSize()
class SerialManager(QtCore.QObject):
valueChanged = QtCore.pyqtSignal(float)
def __init__(self, parent=None):
super().__init__(parent)
self.serial_port = QtSerialPort.QSerialPort("COM3")
self.serial_port.setBaudRate(QtSerialPort.QSerialPort.Baud9600)
self.serial_port.errorOccurred.connect(self.handle_error)
self.serial_port.readyRead.connect(self.handle_ready_read)
self.serial_port.open(QtCore.QIODevice.ReadWrite)
def handle_ready_read(self):
while self.serial_port.canReadLine():
codec = QtCore.QTextCodec.codecForName("UTF-8")
line = codec.toUnicode(self.serial_port.readLine()).strip().strip("\x00")
try:
print(line)
value = float(line)
except ValueError as e:
print("error", e)
else:
self.valueChanged.emit(value)
def handle_error(self, error):
if error == QtSerialPort.QSerialPort.NoError:
return
print(error, self.serial_port.errorString())
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
w1 = MainWindow()
w1.show()
w = MainWindowm()
w.show()
manager = SerialManager()
manager.valueChanged.connect(w1.update_text)
manager.valueChanged.connect(w.update_plot)
sys.exit(app.exec_())
I am writing this program to auto save data to Postgres database when QT Text Edit detects the length of string is greater than 5 characters. The program also displaying current date and time.
note: I had created a save button for save the data in QT Text Edit. But actually I need the data to be saved once the QT Text Edit detects the length is more than 5 characters.
I am facing the difficulties as below:
The time displayed is stop, it is called and show when the apps is launched but after that it is just showing static.
the " if len(self.barcode_in) >= 5: " in line 106 is having error.
I did research on Python schedule, but seems like the minimum interval for scanning is 0.5 seconds. Do I need to use threading function to refresh the clock displayed and scan the length of QT Text Edit?
My full code is as below.
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'savebarcodedatetime.ui'
#
# Created by: PyQt5 UI code generator 5.13.0
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import QTime, QTimer
from PyQt5.QtCore import QDate, Qt
from PyQt5.QtWidgets import QApplication, QLCDNumber
import threading
import psycopg2
#from config import config
from threading import Thread
from datetime import *
import time
from time import time
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.widget = QtWidgets.QWidget(self.centralwidget)
self.widget.setGeometry(QtCore.QRect(50, 10, 721, 531))
self.widget.setObjectName("widget")
self.verticalLayout_2 = QtWidgets.QVBoxLayout(self.widget)
self.verticalLayout_2.setContentsMargins(0, 0, 0, 0)
self.verticalLayout_2.setObjectName("verticalLayout_2")
self.horizontalLayout = QtWidgets.QHBoxLayout()
self.horizontalLayout.setObjectName("horizontalLayout")
spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Minimum)
self.horizontalLayout.addItem(spacerItem)
self.show_time = QtWidgets.QLCDNumber(self.widget) #LCD = show_time
font = QtGui.QFont()
font.setPointSize(16)
self.show_time.setFont(font)
self.show_time.setObjectName("show_time")
self.horizontalLayout.addWidget(self.show_time)
spacerItem1 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
self.horizontalLayout.addItem(spacerItem1)
self.show_date = QtWidgets.QLabel(self.widget)
font = QtGui.QFont()
font.setPointSize(16)
self.show_date.setFont(font)
self.show_date.setObjectName("show_date")
self.horizontalLayout.addWidget(self.show_date)
spacerItem2 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Minimum)
self.horizontalLayout.addItem(spacerItem2)
self.verticalLayout_2.addLayout(self.horizontalLayout)
spacerItem3 = QtWidgets.QSpacerItem(20, 40, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)
self.verticalLayout_2.addItem(spacerItem3)
self.tableWidget = QtWidgets.QTableWidget(self.widget)
self.tableWidget.setObjectName("tableWidget")
self.tableWidget.setColumnCount(0)
self.tableWidget.setRowCount(0)
self.verticalLayout_2.addWidget(self.tableWidget)
spacerItem4 = QtWidgets.QSpacerItem(20, 40, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)
self.verticalLayout_2.addItem(spacerItem4)
self.verticalLayout = QtWidgets.QVBoxLayout()
self.verticalLayout.setObjectName("verticalLayout")
self.barcode_in = QtWidgets.QTextEdit(self.widget)
self.barcode_in.setObjectName("barcode_in")
self.verticalLayout.addWidget(self.barcode_in)
spacerItem5 = QtWidgets.QSpacerItem(20, 20, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Preferred)
self.verticalLayout.addItem(spacerItem5)
self.save_button = QtWidgets.QPushButton(self.widget)
font = QtGui.QFont()
font.setPointSize(24)
self.save_button.setFont(font)
self.save_button.setObjectName("save_button")
self.verticalLayout.addWidget(self.save_button)
spacerItem6 = QtWidgets.QSpacerItem(20, 20, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Preferred)
self.verticalLayout.addItem(spacerItem6)
self.verticalLayout_2.addLayout(self.verticalLayout)
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 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)
self.save_button.clicked.connect(self.save_db)
printoutput.printoutmessage()
todaydate = QTime.currentTime()
print(todaydate.toString(Qt.DefaultLocaleLongDate))
todaydate_str = todaydate.toString("H:mm:ss")
self.show_date.setText(todaydate_str)
print(todaydate.toString(Qt.DefaultLocaleLongDate))
if len(self.barcode_in) >= 5:
barcodedata = self.barcode_in.toPlainText()
insertdb.insert_vendor(barcodedata)
print('barcode save')
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.show_date.setText(_translate("MainWindow", "TextLabel"))
self.save_button.setText(_translate("MainWindow", "Save"))
def save_db(self):
print("save")
#mytext = self.textEdit.toPlainText()
barcodedata = self.barcode_in.toPlainText()
insertdb.insert_vendor(barcodedata)
#barcode_in = ''
today = datetime.now()
print (today.strftime(' %a %d-%m-%Y # %H:%M:%S'))
class insertdb:
def insert_vendor(vendor_name):
""" insert a new vendor into the vendors table """
sql = """INSERT INTO vendors(vendor_name)
VALUES(%s) RETURNING vendor_id;"""
conn = None
vendor_id = None
try:
conn = psycopg2.connect(host="192.168.1.104",
port = 5432, database="suppliers",
user="pi", password="1234")
cur = conn.cursor()
# execute the INSERT statement
cur.execute(sql, (vendor_name,))
# get the generated id back
vendor_id = cur.fetchone()[0]
conn.commit()
cur.close()
except (Exception, psycopg2.DatabaseError) as error:
print(error)
finally:
if conn is not None:
conn.close()
return vendor_id
class printoutput:
def printoutmessage():
print("print output")
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_())
qtextedit can emit signals every time the text on it changes, here is the name and doc.
My suggestion is to connect that signal to you self-defined slot and in the implementation of that method check the length of the new text... is more efficient than polling every "x" seconds for the size of a string.
Now, to the error here:
if len(self.barcode_in) >= 5:
is not valid since
self.barcode_in is actually a widget, you initialized it like doing
self.barcode_in = QtWidgets.QTextEdit(self.widget) therfore makes no sense to compare it against a number, but what you want is to compare the len of the text in that widget, and for this you need the "plain-text" of it (here the doc for that)
I'm trying to create a GUI program using PyQT5. I'm new to programming and Python so if I'm explaining things in the wrong way please correct me.
I have a main window that will contain multiple QLineEdit widgets and corresponding "Clear" buttons to clear the user entered data. The main window also contains "Edit" buttons to dispay specific dialog boxes where the data can also be edited. My example has a "User ID" QLineEdit widget/text box, "Clear" and "Edit" push buttons.
The dialog box that appears when "Edit' is clicked has it's own "Clear" button. If the Clear button in the dialog window is clicked, both the QLineEdit widget in the dialog and main window should be cleared.
Problem: When I inherit the main window class from the dialog class the method, clearUserID(), used to clear the User ID field fails to be invoked.
When I do not inherit from the main window class the clearUserID method works and I am able to clear the dialog QLineEdit (UserIDWin_UserID_lnedt) but not the corresponding widget on the main window (UserID_lnedt). All of the code I've tried to clear the main window QLineEdit widget using the dialog "Clear" button caused my program to crash.
Would somebody please help me to better understand the logic behind these principles and how to get my code working? Thank you.
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(820, 611)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.tabWidget = QtWidgets.QTabWidget(self.centralwidget)
self.tabWidget.setGeometry(QtCore.QRect(0, 0, 801, 551))
self.tabWidget.setObjectName("tabWidget")
self.MainTab = QtWidgets.QWidget()
self.MainTab.setObjectName("MainTab")
self.UserID_Edit_pb = QtWidgets.QPushButton(self.MainTab)
self.UserID_Edit_pb.setGeometry(QtCore.QRect(210, 10, 31, 23))
self.UserID_Edit_pb.setObjectName("UserID_Edit_pb")
self.UserID_Edit_pb.clicked.connect(self.openUserIDWin)
self.UserID_Clear_pb_2 = QtWidgets.QPushButton(self.MainTab)
self.UserID_Clear_pb_2.setGeometry(QtCore.QRect(170, 9, 41, 23))
self.UserID_Clear_pb_2.setObjectName("UserID_Clear_pb_2")
self.UserID_le = QtWidgets.QLineEdit(self.MainTab)
self.label = QtWidgets.QLabel(self.MainTab)
self.label.setGeometry(QtCore.QRect(10, 10, 47, 13))
self.UserID_le.setGeometry(QtCore.QRect(50, 10, 113, 20))
self.UserID_le.setObjectName("UserID_le")
self.tabWidget.addTab(self.MainTab, "")
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 820, 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)
self.tabWidget.setCurrentIndex(0)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
self.UserID_Clear_pb_2.clicked.connect(self.UserID_le.clear)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.UserID_Edit_pb.setText(_translate("MainWindow", "Edit"))
self.UserID_Clear_pb_2.setText(_translate("MainWindow", "Clear"))
self.label.setText(_translate("MainWindow", "User ID"))
self.tabWidget.setTabText(self.tabWidget.indexOf(self.MainTab), _translate("MainWindow", "Tab"))
def openUserIDWin(self):
UserID_value = self.UserID_le.text()
UserIDWin = QtWidgets.QDialog()
ui = Ui_UserIDWin(UserID_value)
ui.setupUi(UserIDWin)
UserIDWin.exec_();
class Ui_UserIDWin(QtWidgets.QMainWindow, Ui_MainWindow):
def __init__(self, userID):
print("The User ID is:" + userID)
self.userID = userID
def setupUi(self, UserIDWin):
UserIDWin.setObjectName("UserIDWin")
UserIDWin.resize(400, 124)
self.UserIDWin_UserID_lnedt = QtWidgets.QLineEdit(UserIDWin)
self.UserIDWin_UserID_lnedt.setText(self.userID)
self.UserIDWin_UserID_lnedt.setGeometry(QtCore.QRect(20, 50, 113, 20))
self.UserIDWin_UserID_lnedt.setObjectName("UserIDWin_UserID_lnedt")
self.UserIDWin_UserID_lbl = QtWidgets.QLabel(UserIDWin)
self.UserIDWin_UserID_lbl.setGeometry(QtCore.QRect(20, 30, 47, 13))
self.UserIDWin_UserID_lbl.setObjectName("UserIDWin_UserID_lbl")
self.UserIDWin_UserIDClear_pushb = QtWidgets.QPushButton(UserIDWin)
self.UserIDWin_UserIDClear_pushb.setGeometry(QtCore.QRect(140, 50, 41, 23))
self.UserIDWin_UserIDClear_pushb.setObjectName("UserIDWin_UserIDClear_pushb")
self.UserIDWin_Cancel_pushb = QtWidgets.QPushButton(UserIDWin)
self.UserIDWin_Cancel_pushb.setGeometry(QtCore.QRect(110, 80, 75, 23))
self.UserIDWin_Cancel_pushb.setObjectName("UserIDWin_Cancel_pushb")
self.UserIDWin_Next_pushb = QtWidgets.QPushButton(UserIDWin)
self.UserIDWin_Next_pushb.setGeometry(QtCore.QRect(190, 80, 75, 23))
self.UserIDWin_Next_pushb.setObjectName("UserIDWin_Next_pushb")
self.retranslateUi(UserIDWin)
QtCore.QMetaObject.connectSlotsByName(UserIDWin)
#If I do not inherit from "QtWidgets.QMainWindow, Ui_MainWindow" the code below works and invokes clearUserId(). However, I then am having problems using SetText on the main window UserId_le text box and the program crashes.
self.UserIDWin_UserIDClear_pushb.clicked.connect(self.clearUserID)
def retranslateUi(self, UserIDWin):
_translate = QtCore.QCoreApplication.translate
UserIDWin.setWindowTitle(_translate("UserIDWin", "Dialog"))
self.UserIDWin_UserID_lbl.setText(_translate("UserIDWin", "User ID"))
self.UserIDWin_UserIDClear_pushb.setText(_translate("UserIDWin", "Clear"))
self.UserIDWin_Cancel_pushb.setText(_translate("UserIDWin", "Cancel"))
self.UserIDWin_Next_pushb.setText(_translate("UserIDWin", "Next"))
def clearUserID(self):
self.UserIDWin_UserID_lnedt.setText('')
# The line below crashes my program if I am able to invoke this method.
#self.Ui_MainWindow.UserID_le.setText('')
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 seems that they have certain clear concepts about inheritance and good practices but others do not like the following:
PyQt recommends not modifying the code generated by Qt Designer because you probably want to modify the GUI in the future and when using pyuic the initial code is overwritten. Another problem is that beginners do not understand that the class generated by Qt Designer is not a widget but an interface that serves to fill another widget, and consequently can not overwrite the methods of the widgets in addition to other problems.
You only have to modify the object of a class from the object of another class if both have the same scope, in your case when wanting to clean the QLineEdit of the main window from the other window is a dangerous task, instead you should do that logic where both windows have the same scope and that is in the openUserIDWin method.
QLineEdit already has the clear() method that allows to clean, it fulfills the same function as setText("") but the first method is more readable.
Considering the above, the solution is:
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(820, 611)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.tabWidget = QtWidgets.QTabWidget(self.centralwidget)
self.tabWidget.setGeometry(QtCore.QRect(0, 0, 801, 551))
self.tabWidget.setObjectName("tabWidget")
self.MainTab = QtWidgets.QWidget()
self.MainTab.setObjectName("MainTab")
self.UserID_Edit_pb = QtWidgets.QPushButton(self.MainTab)
self.UserID_Edit_pb.setGeometry(QtCore.QRect(210, 10, 31, 23))
self.UserID_Edit_pb.setObjectName("UserID_Edit_pb")
self.UserID_Clear_pb_2 = QtWidgets.QPushButton(self.MainTab)
self.UserID_Clear_pb_2.setGeometry(QtCore.QRect(170, 9, 41, 23))
self.UserID_Clear_pb_2.setObjectName("UserID_Clear_pb_2")
self.UserID_le = QtWidgets.QLineEdit(self.MainTab)
self.label = QtWidgets.QLabel(self.MainTab)
self.label.setGeometry(QtCore.QRect(10, 10, 47, 13))
self.UserID_le.setGeometry(QtCore.QRect(50, 10, 113, 20))
self.UserID_le.setObjectName("UserID_le")
self.tabWidget.addTab(self.MainTab, "")
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 820, 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)
self.tabWidget.setCurrentIndex(0)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.UserID_Edit_pb.setText(_translate("MainWindow", "Edit"))
self.UserID_Clear_pb_2.setText(_translate("MainWindow", "Clear"))
self.label.setText(_translate("MainWindow", "User ID"))
self.tabWidget.setTabText(self.tabWidget.indexOf(self.MainTab), _translate("MainWindow", "Tab"))
class Ui_UserIDWin(object):
def setupUi(self, UserIDWin):
UserIDWin.setObjectName("UserIDWin")
UserIDWin.resize(400, 124)
self.UserIDWin_UserID_lnedt = QtWidgets.QLineEdit(UserIDWin)
self.UserIDWin_UserID_lnedt.setGeometry(QtCore.QRect(20, 50, 113, 20))
self.UserIDWin_UserID_lnedt.setObjectName("UserIDWin_UserID_lnedt")
self.UserIDWin_UserID_lbl = QtWidgets.QLabel(UserIDWin)
self.UserIDWin_UserID_lbl.setGeometry(QtCore.QRect(20, 30, 47, 13))
self.UserIDWin_UserID_lbl.setObjectName("UserIDWin_UserID_lbl")
self.UserIDWin_UserIDClear_pushb = QtWidgets.QPushButton(UserIDWin)
self.UserIDWin_UserIDClear_pushb.setGeometry(QtCore.QRect(140, 50, 41, 23))
self.UserIDWin_UserIDClear_pushb.setObjectName("UserIDWin_UserIDClear_pushb")
self.UserIDWin_Cancel_pushb = QtWidgets.QPushButton(UserIDWin)
self.UserIDWin_Cancel_pushb.setGeometry(QtCore.QRect(110, 80, 75, 23))
self.UserIDWin_Cancel_pushb.setObjectName("UserIDWin_Cancel_pushb")
self.UserIDWin_Next_pushb = QtWidgets.QPushButton(UserIDWin)
self.UserIDWin_Next_pushb.setGeometry(QtCore.QRect(190, 80, 75, 23))
self.UserIDWin_Next_pushb.setObjectName("UserIDWin_Next_pushb")
self.retranslateUi(UserIDWin)
QtCore.QMetaObject.connectSlotsByName(UserIDWin)
def retranslateUi(self, UserIDWin):
_translate = QtCore.QCoreApplication.translate
UserIDWin.setWindowTitle(_translate("UserIDWin", "Dialog"))
self.UserIDWin_UserID_lbl.setText(_translate("UserIDWin", "User ID"))
self.UserIDWin_UserIDClear_pushb.setText(_translate("UserIDWin", "Clear"))
self.UserIDWin_Cancel_pushb.setText(_translate("UserIDWin", "Cancel"))
self.UserIDWin_Next_pushb.setText(_translate("UserIDWin", "Next"))
class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.setupUi(self)
self.UserID_Edit_pb.clicked.connect(self.openUserIDWin)
self.UserID_Clear_pb_2.clicked.connect(self.UserID_le.clear)
def openUserIDWin(self):
UserID_value = self.UserID_le.text()
w = UserIDWin(UserID_value)
w.UserIDWin_UserIDClear_pushb.clicked.connect(self.UserID_le.clear)
w.exec_()
class UserIDWin(QtWidgets.QDialog, Ui_UserIDWin):
def __init__(self, userID, parent=None):
super(UserIDWin, self).__init__(parent)
self.setupUi(self)
self.userID = userID
self.UserIDWin_UserID_lnedt.setText(self.userID)
self.UserIDWin_UserIDClear_pushb.clicked.connect(self.UserIDWin_UserID_lnedt.clear)
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
w = MainWindow()
w.show()
sys.exit(app.exec_())
I recommend you read:
http://pyqt.sourceforge.net/Docs/PyQt5/designer.html
QtDesigner changes will be lost after redesign User Interface
I'm doing some preliminary tests before I start programming the GUI I need with pyqt5, and today I found a couple of things that I haven't been able to solve.
My code is the following:
from PyQt5 import QtCore, QtGui, QtWidgets
import time
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(398, 398)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.lineEdit = QtWidgets.QLineEdit(self.centralwidget)
self.lineEdit.setGeometry(QtCore.QRect(30, 40, 131, 61))
self.lineEdit.setText("")
self.lineEdit.setObjectName("lineEdit")
self.lineEdit_2 = QtWidgets.QLineEdit(self.centralwidget)
self.lineEdit_2.setGeometry(QtCore.QRect(30, 120, 131, 61))
self.lineEdit_2.setText("")
self.lineEdit_2.setObjectName("lineEdit_2")
self.lcdNumber = QtWidgets.QLCDNumber(self.centralwidget)
self.lcdNumber.setGeometry(QtCore.QRect(180, 40, 64, 23))
self.lcdNumber.setObjectName("lcdNumber")
self.lcdNumber_2 = QtWidgets.QLCDNumber(self.centralwidget)
self.lcdNumber_2.setGeometry(QtCore.QRect(180, 120, 64, 23))
self.lcdNumber_2.setObjectName("lcdNumber_2")
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 398, 22))
self.menubar.setObjectName("menubar")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.number = 0
self.number_2 = 0
self.lcdNumber.display(self.number)
self.lcdNumber_2.display(self.number_2)
self.lineEdit.returnPressed.connect(self.change_number)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
def change_number(self):
ip = int(self.lineEdit.text())
if ip > self.number:
count = 1
elif ip < self.number:
count = -1
else:
count = 0
while self.number != ip :
self.number += count
self.lcdNumber.display(self.number)
time.sleep(1)
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_())
As you can see I have two QLineEdit boxes and two QLCDNumber for displaying the number that I write in the corresponding QLineEdit.
Problem 1
I'm able to display the number in the QLCDNumber with the following code:
self.lineEdit.returnPressed.connect(self.change_number)
...
def change_number(self):
self.lcdNumber.display(int(self.lineEdit.text()))
However, if I want to change the displayed number one by one with a certain time delay, my code doesn't work as I expect.
For example, if the current number is 0 and I type 10 in the QLineEdit, the program freezes for 10 seconds and then the number 10 is displayed on the QLCDNumber, while I would expect it to be updated second by second. I really can't figure out where the problem is.
Problem 2
I have two QLineEdit and two QLCDNumber, and it doesn't make much sense to write two different functions change_number.
However, I can't find a way for writing a generic function that takes as an input which QLCDNumber will be updated and which QLineEdit will be the input.
In pseudocode, it would be something like this:
self.LINEEDIT_NAME.returnPressed.connect(self.change_number(LINEEDIT_NAME,QLCD_NAME))
...
def change_number(self,LINEEDIT_NAME,QLCD_NAME):
ip = int(self.LINEEDIT_NAME.text())
if ip > self.number:
count = 1
elif ip < self.number:
count = -1
else:
count = 0
while self.number != ip :
self.number += count
self.QLCD_NAME.display(self.number)
time.sleep(1)
but I'm not able to use the LINEEDIT_NAME and QLCD_NAME as variables of the functions.
time.sleep() is a task that blocks the PyQt loop so it is not recommended to use it, the task can easily be substituted with a QTimer.
To facilitate the work we will create a class that inherits from QLCDNumber and that uses a QTimer to update the values
TimerLCDNumber.py
from PyQt5 import QtCore, QtGui, QtWidgets
class TimerLCDNumber(QtWidgets.QLCDNumber):
def __init__(self, *args, **kwargs):
QtWidgets.QLCDNumber.__init__(self, *args, **kwargs)
self.timer = QtCore.QTimer(self)
self.timer.setInterval(1000)
self.timer.timeout.connect(self.onTimeout)
self.finished = self.value()
def setValue(self, value):
self.finished = value
self.timer.start()
def onTimeout(self):
current = self.value()
if self.finished != current:
count = 1 if self.finished > current else -1
self.display(current + count)
else:
self.timer.stop()
This task can be promoted through Qt Designer or simply change, assuming that the file generated by Qt Designer is called design.py:
design.py
self.lcdNumber = QtWidgets.QLCDNumber(self.centralwidget)
self.lcdNumber_2 = QtWidgets.QLCDNumber(self.centralwidget)
to:
self.lcdNumber = TimerLCDNumber(self.centralwidget)
self.lcdNumber_2 = TimerLCDNumber(self.centralwidget)
In addition, the TimerLCDNumber class must be imported:
from TimerLCDNumber import TimerLCDNumber
It is advisable to separate the design from the logic so a new file called main.py is created that imports the design class and implements the logic:
main.py
from PyQt5 import QtCore, QtGui, QtWidgets
from design import Ui_MainWindow
class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
def __init__(self, *args, **kwargs):
QtWidgets.QMainWindow.__init__(self, *args, **kwargs)
self.setupUi(self)
self.lineEdit.returnPressed.connect(lambda: self.lcdNumber.setValue(int(self.lineEdit.text())))
self.lineEdit_2.returnPressed.connect(lambda: self.lcdNumber_2.setValue(int(self.lineEdit_2.text())))
self.lcdNumber.display(0)
self.lcdNumber_2.display(0)
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
w = MainWindow()
w.show()
sys.exit(app.exec_())
At the end in our folder we must have the following structure:
.
├── design.py
├── main.py
└── TimerLCDNumber.py
A possible solution for the second question is to use the lambda functions:
first option:
self.lineEdit.returnPressed.connect(lambda: self.lcdNumber.setValue(int(self.lineEdit.text())))
self.lineEdit_2.returnPressed.connect(lambda: self.lcdNumber_2.setValue(int(self.lineEdit_2.text())))
second option:
self.lineEdit.returnPressed.connect(lambda: change_number(self.lineEdit, self.lcdNumber))
self.lineEdit_2.returnPressed.connect(lambda: change_number(self.lineEdit_2, self.lcdNumber_2))
def change_number(self,LINEEDIT_NAME,QLCD_NAME):
QLCD_NAME.setValue(int(LINEEDIT_NAME.text()))
The complete code can be found at the following link.