I'm using PyQt5 designer to make a little application. I mostly work with designer rather than building from scratch so this might be a silly question. Basically i have a main menu and a "create" button that when clicked will open up the other pyqt5 .py file (also created in designer) i have been working on.
So far i complied the ui files into .py files and imported the popup window that i want to be able to generate more than one of and then i use this code to some success:
I have not added any additonal code to the converted ui files excpect this function:
Here is some code from my mainmenu and popoutwindow .py files:
this is the setupUi being called from my file im trying to replicate
class BookPopout(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(772, 685)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.lastNameLabel = QtWidgets.QLabel(self.centralwidget)
self.lastNameLabel.setGeometry(QtCore.QRect(20, 110, 60, 17))
self.lastNameLabel.setObjectName("lastNameLabel")
self.cityEntry = QtWidgets.QLineEdit(self.centralwidget)
self.cityEntry.setGeometry(QtCore.QRect(20, 310, 391, 27))
self.cityEntry.setReadOnly(True)
self.cityEntry.setObjectName("cityEntry")
self.bookTable = QtWidgets.QTableWidget(self.centralwidget)
self.bookTable.setGeometry(QtCore.QRect(470, 10, 281, 481))
font = QtGui.QFont()
font.setPointSize(7)
self.bookTable.setFont(font)
self.bookTable.setAutoFillBackground(False)
self.bookTable.setEditTriggers(QtWidgets.QAbstractItemView.NoEditTriggers)
self.bookTable.setRowCount(1)
self.bookTable.setColumnCount(1)
self.bookTable.setObjectName("bookTable")
item = QtWidgets.QTableWidgetItem()
self.bookTable.setItem(0, 0, item)
self.bookTable.horizontalHeader().setVisible(False)
self.bookTable.horizontalHeader().setCascadingSectionResizes(False)
self.bookTable.horizontalHeader().setDefaultSectionSize(100)
self.bookTable.horizontalHeader().setStretchLastSection(True)
self.addressLineOneEntry = QtWidgets.QLineEdit(self.centralwidget)
self.addressLineOneEntry.setGeometry(QtCore.QRect(20, 190, 391, 27))
self.addressLineOneEntry.setReadOnly(True)
self.addressLineOneEntry.setObjectName("addressLineOneEntry")
self.stateEntry = QtWidgets.QLineEdit(self.centralwidget)
self.stateEntry.setGeometry(QtCore.QRect(20, 380, 391, 27))
self.stateEntry.setReadOnly(True)
self.stateEntry.setObjectName("stateEntry")
self.firstNameEntry = QtWidgets.QLineEdit(self.centralwidget)
self.firstNameEntry.setGeometry(QtCore.QRect(20, 70, 391, 27))
self.firstNameEntry.setReadOnly(True)
self.firstNameEntry.setObjectName("firstNameEntry")
self.streetAddressLabel = QtWidgets.QLabel(self.centralwidget)
self.streetAddressLabel.setGeometry(QtCore.QRect(20, 170, 83, 17))
self.streetAddressLabel.setObjectName("streetAddressLabel")
self.streetAddressTwoLabel = QtWidgets.QLabel(self.centralwidget)
self.streetAddressTwoLabel.setGeometry(QtCore.QRect(20, 240, 220, 17))
self.streetAddressTwoLabel.setObjectName("streetAddressTwoLabel")
self.phoneNumberLabel = QtWidgets.QLabel(self.centralwidget)
self.phoneNumberLabel.setGeometry(QtCore.QRect(20, 480, 87, 17))
self.phoneNumberLabel.setObjectName("phoneNumberLabel")
self.addressLineTwoEntry = QtWidgets.QLineEdit(self.centralwidget)
self.addressLineTwoEntry.setGeometry(QtCore.QRect(20, 260, 391, 27))
self.addressLineTwoEntry.setReadOnly(True)
self.addressLineTwoEntry.setObjectName("addressLineTwoEntry")
self.phoneNumberEntry = QtWidgets.QLineEdit(self.centralwidget)
self.phoneNumberEntry.setGeometry(QtCore.QRect(20, 500, 391, 27))
self.phoneNumberEntry.setReadOnly(True)
self.phoneNumberEntry.setObjectName("phoneNumberEntry")
self.firstNameLabel = QtWidgets.QLabel(self.centralwidget)
self.firstNameLabel.setGeometry(QtCore.QRect(20, 40, 62, 17))
self.firstNameLabel.setObjectName("firstNameLabel")
self.cityLabel = QtWidgets.QLabel(self.centralwidget)
self.cityLabel.setGeometry(QtCore.QRect(20, 290, 23, 17))
self.cityLabel.setObjectName("cityLabel")
self.stateLabel = QtWidgets.QLabel(self.centralwidget)
self.stateLabel.setGeometry(QtCore.QRect(20, 350, 29, 17))
self.stateLabel.setObjectName("stateLabel")
self.zipEntry = QtWidgets.QLineEdit(self.centralwidget)
self.zipEntry.setGeometry(QtCore.QRect(20, 440, 391, 27))
self.zipEntry.setReadOnly(True)
self.zipEntry.setObjectName("zipEntry")
self.zipLabel = QtWidgets.QLabel(self.centralwidget)
self.zipLabel.setGeometry(QtCore.QRect(20, 410, 18, 17))
self.zipLabel.setObjectName("zipLabel")
self.emailEntry = QtWidgets.QLineEdit(self.centralwidget)
self.emailEntry.setGeometry(QtCore.QRect(20, 550, 391, 27))
self.emailEntry.setObjectName("emailEntry")
self.label = QtWidgets.QLabel(self.centralwidget)
self.label.setGeometry(QtCore.QRect(20, 530, 80, 17))
self.label.setObjectName("label")
self.confirmNewPersonButton = QtWidgets.QPushButton(self.centralwidget)
self.confirmNewPersonButton.setGeometry(QtCore.QRect(20, 590, 85, 27))
self.confirmNewPersonButton.setObjectName("confirmNewPersonButton")
self.lastNameEntry = QtWidgets.QLineEdit(self.centralwidget)
self.lastNameEntry.setEnabled(True)
self.lastNameEntry.setGeometry(QtCore.QRect(20, 130, 391, 27))
self.lastNameEntry.setText("")
self.lastNameEntry.setReadOnly(True)
self.lastNameEntry.setObjectName("lastNameEntry")
self.sortComboBox = QtWidgets.QComboBox(self.centralwidget)
self.sortComboBox.setGeometry(QtCore.QRect(500, 530, 101, 31))
self.sortComboBox.setObjectName("sortComboBox")
self.sortByLabel = QtWidgets.QLabel(self.centralwidget)
self.sortByLabel.setGeometry(QtCore.QRect(570, 500, 71, 31))
font = QtGui.QFont()
font.setPointSize(14)
self.sortByLabel.setFont(font)
self.sortByLabel.setObjectName("sortByLabel")
self.sortButton = QtWidgets.QPushButton(self.centralwidget)
self.sortButton.setGeometry(QtCore.QRect(600, 530, 111, 31))
font = QtGui.QFont()
font.setPointSize(14)
self.sortButton.setFont(font)
self.sortButton.setObjectName("sortButton")
self.addNewPersonButton = QtWidgets.QPushButton(self.centralwidget)
self.addNewPersonButton.setGeometry(QtCore.QRect(40, 10, 101, 27))
self.addNewPersonButton.setObjectName("addNewPersonButton")
self.editEntryButton = QtWidgets.QPushButton(self.centralwidget)
self.editEntryButton.setGeometry(QtCore.QRect(170, 10, 111, 27))
self.editEntryButton.setObjectName("editEntryButton")
self.confirmEditButton = QtWidgets.QPushButton(self.centralwidget)
self.confirmEditButton.setGeometry(QtCore.QRect(20, 590, 111, 27))
self.confirmEditButton.setObjectName("confirmEditButton")
self.deleteEntryButton = QtWidgets.QPushButton(self.centralwidget)
self.deleteEntryButton.setGeometry(QtCore.QRect(300, 10, 111, 27))
self.deleteEntryButton.setObjectName("deleteEntryButton")
self.sortByLabel_2 = QtWidgets.QLabel(self.centralwidget)
self.sortByLabel_2.setGeometry(QtCore.QRect(530, 570, 131, 31))
font = QtGui.QFont()
font.setPointSize(12)
self.sortByLabel_2.setFont(font)
self.sortByLabel_2.setObjectName("sortByLabel_2")
self.lineEdit = QtWidgets.QLineEdit(self.centralwidget)
self.lineEdit.setGeometry(QtCore.QRect(500, 600, 101, 31))
self.lineEdit.setObjectName("lineEdit")
self.sortButton_2 = QtWidgets.QPushButton(self.centralwidget)
self.sortButton_2.setGeometry(QtCore.QRect(600, 600, 111, 31))
font = QtGui.QFont()
font.setPointSize(14)
self.sortButton_2.setFont(font)
self.sortButton_2.setObjectName("sortButton_2")
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setEnabled(True)
self.menubar.setGeometry(QtCore.QRect(0, 0, 772, 27))
self.menubar.setObjectName("menubar")
self.menuOpen = QtWidgets.QMenu(self.menubar)
self.menuOpen.setObjectName("menuOpen")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.actionSave = QtWidgets.QAction(MainWindow)
self.actionSave.setObjectName("actionSave")
self.actionSave_as = QtWidgets.QAction(MainWindow)
self.actionSave_as.setObjectName("actionSave_as")
self.actionClose = QtWidgets.QAction(MainWindow)
self.actionClose.setObjectName("actionClose")
self.menuOpen.addAction(self.actionSave)
self.menuOpen.addSeparator()
self.menuOpen.addAction(self.actionSave_as)
self.menuOpen.addSeparator()
self.menuOpen.addAction(self.actionClose)
self.menubar.addAction(self.menuOpen.menuAction())
QtCore.QMetaObject.connectSlotsByName(MainWindow)
Here is my mainmenu py file:
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(255, 410)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.createNewBookButton = QtWidgets.QPushButton(self.centralwidget)
self.createNewBookButton.setGeometry(QtCore.QRect(40, 220, 171, 41))
self.createNewBookButton.setObjectName("createNewBookButton")
self.createNewBookButton.clicked.connect(self.openNewBook)
self.openExistingBookButton = QtWidgets.QPushButton(self.centralwidget)
self.openExistingBookButton.setGeometry(QtCore.QRect(40, 280, 171, 41))
self.openExistingBookButton.setObjectName("openExistingBookButton")
self.quitProgramButton = QtWidgets.QPushButton(self.centralwidget)
self.quitProgramButton.setGeometry(QtCore.QRect(40, 340, 171, 41))
self.quitProgramButton.setObjectName("quitProgramButton")
self.mainImage = QtWidgets.QGraphicsView(self.centralwidget)
self.mainImage.setGeometry(QtCore.QRect(10, 10, 231, 192))
self.mainImage.setObjectName("mainImage")
MainWindow.setCentralWidget(self.centralwidget)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def openNewBook(self):
self.popWin = QtWidgets.QMainWindow()
self.bookUI = bookPopout.BookPopout()
self.bookUI.setupUi(self.popWin)
self.popWin.show()
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
This works great for opening up ONE extra window, which stays open while my main window is open which is what i want, but then when i go to click to make another window appear, it just replaces the one i already had up, so i can only seem to have one extra at a time.
I figure that my old window is being referenced by self.popWin , and then being replaced over and over so my question i guess is what is the best way to go about "generating" windows instead of just referencing the same window over and over.. i tried to remove the "self" part but then the window just dosent even appear when i go to create a new window so i am kind of lost
for example i would expect to be able to write something like this but im not really sure how to go about doing so
currentWindows = []
newPopWin = QtWidgets.QMainWindow()
newBookUI = BookPopout()
newBookUI.setupUi(newPopWin)
newPopWin.show()
currentWindows.append(newPopWin)
this would be ideal so i could keep track of all current open windows so i may terminate them all once i close my main menu.
Any help would be appreciated to put me on the right track, i have tried looking up solutions but lots of examples are not using code converted from a UI file.
The problem is simple, we are overwriting an attribute and at that moment the previous element is deleted, for that reason only a window. As you point out the solution is to store it in a list.
But before that, I recommend you not to write your logic in the .py generated by Qt Designer since for example let's say that you want to modify something of the design, then when generating the new .py it will erase all your logic. What PyQt recommends is to use create another file where you generate the logic adviritiendote with the message: # WARNING! All changes made in this file will be lost!. So restore the previous files I called bookPopup.py and mainmenu.py by removing the openNewBook. Following the docs recommendation we obtain the following:
main.py
from PyQt5 import QtCore, QtGui, QtWidgets
import bookPopout
import mainmenu
class BookPopoutWindow(QtWidgets.QMainWindow, bookPopout.BookPopout):
def __init__(self, parent=None):
super(BookPopoutWindow, self).__init__(parent)
self.setupUi(self)
class MainMenu(QtWidgets.QMainWindow, mainmenu.Ui_MainWindow):
def __init__(self, parent=None):
super(MainMenu, self).__init__(parent)
self.setupUi(self)
self.createNewBookButton.clicked.connect(self.openNewBook)
self.popups = []
#QtCore.pyqtSlot()
def openNewBook(self):
popWin = BookPopoutWindow()
popWin.show()
self.popups.append(popWin)
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
w = MainMenu()
w.show()
sys.exit(app.exec_())
PyQt5 Opening Multiple Windows/Widgets and Closing them
import sys
from PyQt5.QtWidgets import QWidget, QPushButton, QApplication, QAction
import random
class Widget2(QWidget):
def __init__(self):
super().__init__()
w2btn = QPushButton('Another Widget ' +
str(random.randrange(5, 100, 5)), self)
w2btn.clicked.connect(self.w2btnclicked)
w2btn.resize(w2btn.sizeHint())
w2btn.move(50, 50)
def w2btnclicked(self):
print("Widget 2 btn clicked")
class Widget1(QWidget):
def __init__(self):
super().__init__()
self.start = 50
self.end = 50
quit = QAction("Quit", self)
quit.triggered.connect(self.close)
addbtn = QPushButton('Add Window', self)
addbtn.clicked.connect(self.addbtnclicked)
addbtn.resize(addbtn.sizeHint())
addbtn.move(50, 50)
quitbtn = QPushButton('Quit', self)
quitbtn.clicked.connect(QApplication.instance().quit)
quitbtn.resize(quitbtn.sizeHint())
quitbtn.move(50, 100)
self.popups = []
def addbtnclicked(self):
print("Add Button Clicked!!")
wdgt2 = Widget2()
wdgt2.show()
if self.start > 1600:
self.start = 50
self.end = self.end + 250
wdgt2.setGeometry(self.start, self.end, 200, 200)
self.popups.append(wdgt2)
self.start = self.start + 250
def closeEvent(self, event):
print("In Close Event")
QApplication.closeAllWindows()
def main():
app = QApplication(sys.argv)
ex = Widget1()
ex.show()
ex.setGeometry(800, 600, 200, 200)
sys.exit(app.exec_())
if __name__ == '__main__':
main()
Related
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_())
im pretty new to working with pyqt5 in python, everything is kinda running how it is supposed to be. the only issue i have is that when im triggering to start the function stepperaction(self, index) with the "START" button, i can see the code running in the console, but the UI crashes while the code is running if i click anywhere on the ui with my mouse. i would like to be able to press the "STOP" button in the UI even while the function is running. How am i able to fix this?
# -*- coding: utf-8 -*-
# Created by: PyQt5 UI code generator 5.13.0
import time
import sys
# import RPi.GPIO as GPIO
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import QVariant
stepcount = 0
class Ui_mainWindow(object):
def setupUi(self, mainWindow):
mainWindow.setObjectName("mainWindow")
mainWindow.resize(557, 320)
self.centralwidget = QtWidgets.QWidget(mainWindow)
self.centralwidget.setEnabled(True)
self.centralwidget.setObjectName("centralwidget")
self.pushButton = QtWidgets.QPushButton(self.centralwidget)
self.pushButton.setGeometry(QtCore.QRect(360, 40, 75, 23))
self.pushButton.setObjectName("pushButton")
self.pushButton_4 = QtWidgets.QPushButton(self.centralwidget)
self.pushButton_4.setGeometry(QtCore.QRect(360, 70, 75, 23))
self.pushButton_4.setObjectName("pushButton")
self.pushButton_2 = QtWidgets.QPushButton(self.centralwidget)
self.pushButton_2.setGeometry(QtCore.QRect(270, 70, 75, 23))
self.pushButton_2.setObjectName("pushButton_2")
self.comboBox = QtWidgets.QComboBox(self.centralwidget)
self.comboBox.setGeometry(QtCore.QRect(150, 40, 101, 22))
self.comboBox.setEditable(False)
self.comboBox.setObjectName("comboBox")
self.comboBox.addItem("", QVariant(10*1600))
self.comboBox.addItem("", QVariant(20))
self.comboBox.addItem("", QVariant(30))
self.comboBox.addItem("", QVariant(40))
self.comboBox.addItem("", QVariant(50))
self.label = QtWidgets.QLabel(self.centralwidget)
self.label.setGeometry(QtCore.QRect(20, 30, 121, 31))
font = QtGui.QFont()
font.setPointSize(12)
self.label.setFont(font)
self.label.setObjectName("label")
self.progressBar = QtWidgets.QProgressBar(self.centralwidget)
self.progressBar.setGeometry(QtCore.QRect(20, 250, 118, 23))
self.progressBar.setProperty("value", 24)
self.progressBar.setObjectName("progressBar")
self.pushButton_3 = QtWidgets.QPushButton(self.centralwidget)
self.pushButton_3.setGeometry(QtCore.QRect(270, 40, 75, 23))
self.pushButton_3.setObjectName("pushButton_3")
self.label_2 = QtWidgets.QLabel(self.centralwidget)
self.label_2.setGeometry(QtCore.QRect(400, 252, 71, 21))
self.label_2.setObjectName("label_2")
self.label_3 = QtWidgets.QLabel(self.centralwidget)
self.label_3.setGeometry(QtCore.QRect(480, 252, 51, 21))
self.label_3.setObjectName("label_3")
mainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(mainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 557, 21))
self.menubar.setObjectName("menubar")
self.menuSmart_Spray_Booth_Configuration = QtWidgets.QMenu(self.menubar)
self.menuSmart_Spray_Booth_Configuration.setObjectName("menuSmart_Spray_Booth_Configuration")
mainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(mainWindow)
self.statusbar.setObjectName("statusbar")
mainWindow.setStatusBar(self.statusbar)
self.menubar.addAction(self.menuSmart_Spray_Booth_Configuration.menuAction())
self.retranslateUi(mainWindow)
QtCore.QMetaObject.connectSlotsByName(mainWindow)
self.comboBox.activated.connect(self.handleactivated)
self.pushButton.clicked.connect(lambda: self.stepperaction(index=self.comboBox.currentIndex()))
self.pushButton_2.clicked.connect(lambda: self.stop())
def handleactivated(self, index):
print(self.comboBox.itemText(index), "handle")
print(self.comboBox.itemData(index), "handle")
self.label_3.setText(self.comboBox.itemText(index))
def retranslateUi(self, mainWindow):
_translate = QtCore.QCoreApplication.translate
mainWindow.setWindowTitle(_translate("mainWindow", "Smart Spray Booth - Configuration"))
self.pushButton.setText(_translate("mainWindow", "START"))
self.pushButton_2.setText(_translate("mainWindow", "STOP"))
self.pushButton_3.setText(_translate("mainWindow", "Nullpunkt"))
self.comboBox.setItemText(0, _translate("mainWindow", "5cm"))
self.comboBox.setItemText(1, _translate("mainWindow", "10cm"))
self.comboBox.setItemText(2, _translate("mainWindow", "15cm"))
self.comboBox.setItemText(3, _translate("mainWindow", "20cm"))
self.comboBox.setItemText(4, _translate("mainWindow", "25cm"))
self.label.setText(_translate("mainWindow", "Bauteilgröße:"))
self.label_2.setText(_translate("mainWindow", "Bauteilgröße:"))
self.label_3.setText(_translate("mainWindow", "0 cm"))
self.menuSmart_Spray_Booth_Configuration.setTitle(_translate("mainWindow", "Smart Spray Booth - Configuration"))
if self.comboBox.currentTextChanged:
print(self.comboBox.currentData(), "from if")
def stop(self):
print("programm wird beendet")
sys.exit()
def stepperaction(self, index):
# GPIO.setmode(GPIO.BOARD) # read the pin as board instead of BCM pin
global stepcount
stepcount = self.comboBox.itemData(index)
print(stepcount, "this is given step")
# return stepcount
FastSpeed = 0.0001 # old = 0.001 Change this depends on your stepper motor
LowSpeed = 0.0001 # old = 0.001 Change this depends on your stepper motor
counter = 0
countery = 0
while True and counter < 3:
print("Move Up", stepcount, "steps")
for i in range(stepcount):
countery = countery + 1
print(countery)
time.sleep(LowSpeed)
print(countery)
time.sleep(LowSpeed)
time.sleep(1)
print("Move Down", stepcount, "steps")
for i in range(stepcount):
countery = countery + 1
print(countery)
time.sleep(FastSpeed)
print(countery)
time.sleep(FastSpeed)
time.sleep(1)
counter += 1
print("success")
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_())
I can't test on PyQt5, but on PySide you just need to pass the name of the function to connect, not execute it. It might also be better to avoid using lambdas in QT slots.
Try this modification:
....
self.pushButton.clicked.connect(self.stepperaction)
....
def stepperaction(self, index=None):
if index is None:
index = self.comboBox.currentIndex()
# GPIO.setmode(GPIO.BOARD) # read the pin as board instead of BCM pin
global stepcount
....
This question already has an answer here:
Python Sqlite3 - Data is not saved permanently
(1 answer)
Closed 3 years ago.
from PyQt5 import QtCore, QtGui, QtWidgets
import sqlite3
class Ui_Form(object):
def setupUi(self, Form):
Form.setObjectName("Form")
Form.resize(1039, 584)
self.image_label = QtWidgets.QLabel(Form)
self.image_label.setGeometry(QtCore.QRect(10, 0, 801, 511))
self.image_label.setObjectName("image_label")
self.control_bt = QtWidgets.QPushButton(Form)
self.control_bt.setGeometry(QtCore.QRect(890, 340, 93, 28))
self.control_bt.setObjectName("control_bt")
self.label_2 = QtWidgets.QLabel(Form)
self.label_2.setGeometry(QtCore.QRect(860, 240, 158, 51))
self.label_2.setObjectName("label_2")
self.lineEdit_2 = QtWidgets.QLineEdit(Form)
self.lineEdit_2.setGeometry(QtCore.QRect(860, 280, 158, 24))
self.lineEdit_2.setObjectName("lineEdit_2")
self.pushButton = QtWidgets.QPushButton(Form)
self.pushButton.setGeometry(QtCore.QRect(890, 310, 93, 28))
self.pushButton.setObjectName("pushButton")
self.lineEdit = QtWidgets.QLineEdit(Form)
self.lineEdit.setGeometry(QtCore.QRect(880, 230, 113, 22))
self.lineEdit.setObjectName("lineEdit")
self.label = QtWidgets.QLabel(Form)
self.label.setGeometry(QtCore.QRect(910, 210, 55, 16))
self.label.setObjectName("label")
self.retranslateUi(Form)
QtCore.QMetaObject.connectSlotsByName(Form)
def retranslateUi(self, Form):
_translate = QtCore.QCoreApplication.translate
Form.setWindowTitle(_translate("Form", "Face detection"))
self.image_label.setText(_translate("Form", " FACE DETECTION"))
self.control_bt.setText(_translate("Form", "Start"))
self.label_2.setText(_translate("Form", " Enter name of person"))
self.pushButton.setText(_translate("Form", "click to save"))
self.label.setText(_translate("Form", "enter id"))
self.pushButton.clicked.connect(self.InsertData)``
def InsertData(self):
import sqlite3
id=self.lineEdit.text()
name=str(self.lineEdit_2.text())
conn=sqlite3.connect('B.db')
curs=conn.cursor()
curs.execute("INSERT INTO register (id,name) VALUES ('"+id+"','"+name+"');")
print(id,name)
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
Form = QtWidgets.QWidget()
ui = Ui_Form()
ui.setupUi(Form)
Form.show()
sys.exit(app.exec_())
you do not need to import sqlite3 within your function again, then after your query commit your connection
conn.commit()
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_())