How insert data to qtablewidget row by row - pyqt

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_())

Related

How to open multiple instances of one QDialog object in PyQt5? [duplicate]

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()

How to create Windows GUI application to play videos

This is the Code i am trying below.
I want to play .avi, .mp4, etc.
I am able to select video but unable to play.
import sys
from PyQt5 import QtCore, QtGui, QtWidgets, QtMultimedia, QtMultimediaWidgets
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtMultimedia import QMediaContent, QMediaPlayer
from PyQt5.QtMultimediaWidgets import QVideoWidget
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
self.mediaPlayer = QtMultimedia.QMediaPlayer(None, QtMultimedia.QMediaPlayer.VideoSurface)
videoWidget = QtMultimediaWidgets.QVideoWidget()
MainWindow.setObjectName("MainWindow")
MainWindow.resize(881, 578)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.gridLayout = QtWidgets.QGridLayout(self.centralwidget)
self.gridLayout.setObjectName("gridLayout")
self.frame = QtWidgets.QFrame(self.centralwidget)
self.frame.setFrameShape(QtWidgets.QFrame.StyledPanel)
self.frame.setFrameShadow(QtWidgets.QFrame.Raised)
self.frame.setObjectName("frame")
self.gridLayout_2 = QtWidgets.QGridLayout(self.frame)
self.gridLayout_2.setObjectName("gridLayout_2")
self.widget = QVideoWidget(self.frame)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.widget.sizePolicy().hasHeightForWidth())
self.widget.setSizePolicy(sizePolicy)
self.widget.setMinimumSize(QtCore.QSize(711, 471))
self.widget.setMaximumSize(QtCore.QSize(711, 471))
self.widget.setObjectName("widget")
self.gridLayout_2.addWidget(self.widget, 0, 0, 3, 1)
self.audiobar = QtWidgets.QSlider(self.frame)
self.audiobar.setMinimumSize(QtCore.QSize(22, 160))
self.audiobar.setMaximumSize(QtCore.QSize(22, 160))
self.audiobar.setOrientation(QtCore.Qt.Vertical)
self.audiobar.setObjectName("audiobar")
self.gridLayout_2.addWidget(self.audiobar, 2, 2, 1, 1)
self.videobar = QtWidgets.QSlider(self.frame)
self.videobar.setMinimumSize(QtCore.QSize(711, 22))
self.videobar.setMaximumSize(QtCore.QSize(711, 22))
self.videobar.setOrientation(QtCore.Qt.Horizontal)
self.videobar.setObjectName("videobar")
self.gridLayout_2.addWidget(self.videobar, 3, 0, 1, 1)
self.frame_2 = QtWidgets.QFrame(self.frame)
self.frame_2.setMinimumSize(QtCore.QSize(120, 111))
self.frame_2.setMaximumSize(QtCore.QSize(120, 111))
self.frame_2.setFrameShape(QtWidgets.QFrame.StyledPanel)
self.frame_2.setFrameShadow(QtWidgets.QFrame.Raised)
self.frame_2.setObjectName("frame_2")
self.playbtn = QtWidgets.QPushButton(self.frame_2)
self.playbtn.setGeometry(QtCore.QRect(20, 10, 75, 23))
self.playbtn.setObjectName("playbtn")
self.playbtn.setEnabled(False)
self.pausebtn = QtWidgets.QPushButton(self.frame_2)
self.pausebtn.setGeometry(QtCore.QRect(20, 40, 75, 23))
self.pausebtn.setObjectName("pausebtn")
self.stopbtn = QtWidgets.QPushButton(self.frame_2)
self.stopbtn.setGeometry(QtCore.QRect(20, 70, 75, 23))
self.stopbtn.setObjectName("stopbtn")
self.gridLayout_2.addWidget(self.frame_2, 0, 2, 1, 1)
spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
self.gridLayout_2.addItem(spacerItem, 0, 1, 1, 1)
self.gridLayout.addWidget(self.frame, 1, 0, 1, 1)
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 881, 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.actionClose = QtWidgets.QAction(MainWindow)
self.actionClose.setObjectName("actionClose")
self.menuFile.addAction(self.actionOpen)
self.menuFile.addAction(self.actionClose)
self.menubar.addAction(self.menuFile.menuAction())
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
self.mediaPlayer.setVideoOutput(videoWidget)
self.actionOpen.triggered.connect(self.openFile)
self.playbtn.clicked.connect(self.play)
self.mediaPlayer.setVideoOutput(videoWidget)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MPlayer"))
self.playbtn.setText(_translate("MainWindow", "Play"))
self.pausebtn.setText(_translate("MainWindow", "Pause"))
self.stopbtn.setText(_translate("MainWindow", "Stop"))
self.menuFile.setTitle(_translate("MainWindow", "File"))
self.actionOpen.setText(_translate("MainWindow", "Open"))
self.actionClose.setText(_translate("MainWindow", "Close"))
def openFile(self):
fileName, _ = QFileDialog.getOpenFileName(None, "Select Video", " ", "Video Files (*.mp4 *.avi)",
QtCore.QDir.homePath())
if fileName != '':
self.mediaPlayer.setMedia(
QtMultimedia.QMediaContent(QtCore.QUrl.fromLocalFile(fileName)))
self.playbtn.setEnabled(True)
self.statusbar.showMessage(fileName)
self.play()
def play(self):
if self.mediaPlayer.state() == QtMultimedia.QMediaPlayer.PlayingState:
self.mediaPlayer.pause()
else:
self.mediaPlayer.play()
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_())
You set the video output to videoWidget, but you didn't add it to the interface.
You already created a video widget, though, and it is self.widget, so you just have to use that (and only once):
self.mediaPlayer.setVideoOutput(self.widget)
Note that you are using the output of pyuic for your program, which is highly discouraged. Follow the guidelines about using Designer instead.

Display real time data with PyQt and Raspberry

I am currently using the Raspberry Pi 3 to collect data from a temperature and humidity sensor (DHT11) and then display it in a QTextEdit using PyQt4.
The problem is that I would like to do this in real time but I cannot update the data automatically into the interface. Does anyone have any idea about how I can do this?
PS: Here is the link to install Adafruit if you are interested.
Have a good day,
import time
import Adafruit_DHT
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
try:
_encoding = QtGui.QApplication.UnicodeUTF8
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig)
class Ui_Room1(object):
def AffichT(self):
sensor=11
pin=4
humidity, temperature = Adafruit_DHT.read_retry(sensor, pin)
if temperature is not None:
print('Temp={0:0.1f}* Humidity={1:0.1f}%'.format(temperature, humidity))
return str(temperature)
else:
print('Failed to get reading. Try again!')
sys.exit(1)
def AffichH(self):
sensor=11
pin=4
humidity, temperature = Adafruit_DHT.read_retry(sensor, pin)
if humidity is not None:
return str(humidity)
else:
print('Failed to get reading. Try again!')
sys.exit(1)
def setupUi(self, Room1):
Room1.setObjectName(_fromUtf8("Room1"))
Room1.resize(674, 422)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(Room1.sizePolicy().hasHeightForWidth())
Room1.setSizePolicy(sizePolicy)
Room1.setMouseTracking(False)
Room1.setStyleSheet(_fromUtf8("image: url(:/gradient1/Images/gradient1.png);\n"
"\n"
""))
self.centralwidget = QtGui.QWidget(Room1)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.centralwidget.sizePolicy().hasHeightForWidth())
self.centralwidget.setSizePolicy(sizePolicy)
self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
self.graphicsView = QtGui.QGraphicsView(self.centralwidget)
self.graphicsView.setGeometry(QtCore.QRect(610, 30, 41, 41))
self.graphicsView.setStyleSheet(_fromUtf8("background-color: transparent;\n"
"background-image: url(:/gradient1/Images/logout.png);\n"
"background-repeat: no;"))
self.graphicsView.setFrameShape(QtGui.QFrame.NoFrame)
self.graphicsView.setObjectName(_fromUtf8("graphicsView"))
self.label = QtGui.QLabel(self.centralwidget)
self.label.setGeometry(QtCore.QRect(270, 50, 131, 31))
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.label.sizePolicy().hasHeightForWidth())
self.label.setSizePolicy(sizePolicy)
font = QtGui.QFont()
font.setPointSize(18)
font.setBold(True)
font.setWeight(75)
self.label.setFont(font)
self.label.setStyleSheet(_fromUtf8("image : none;\n"
"color: #fff;\n"
"background-color: transparent;"))
self.label.setObjectName(_fromUtf8("label"))
self.label_2 = QtGui.QLabel(self.centralwidget)
self.label_2.setGeometry(QtCore.QRect(140, 170, 101, 61))
self.label_2.setStyleSheet(_fromUtf8("image: none;\n"
"color: #fff;\n"
"background-color: #347;"))
self.label_2.setObjectName(_fromUtf8("label_2"))
self.label_3 = QtGui.QLabel(self.centralwidget)
self.label_3.setGeometry(QtCore.QRect(140, 260, 101, 61))
self.label_3.setStyleSheet(_fromUtf8("image: none;\n"
"color: #fff;\n"
"background-color: #347;"))
self.label_3.setObjectName(_fromUtf8("label_3"))
self.label_4 = QtGui.QLabel(self.centralwidget)
self.label_4.setGeometry(QtCore.QRect(300, 170, 101, 61))
self.label_4.setStyleSheet(_fromUtf8("image: none;\n"
"color: #fff;\n"
"background-color: #347;"))
temp = self.AffichT()
self.label_4.setText(_fromUtf8(temp+"°"))
self.label_4.setObjectName(_fromUtf8("label_4"))
self.label_5 = QtGui.QLabel(self.centralwidget)
self.label_5.setGeometry(QtCore.QRect(300, 260, 101, 61))
self.label_5.setStyleSheet(_fromUtf8("image: none;\n"
"color: #fff;\n"
"background-color: #347;"))
hum = self.AffichH()
self.label_5.setText(_fromUtf8(hum)+"%")
self.label_5.setObjectName(_fromUtf8("label_5"))
Room1.setCentralWidget(self.centralwidget)
self.retranslateUi(Room1)
QtCore.QMetaObject.connectSlotsByName(Room1)
def retranslateUi(self, Room1):
Room1.setWindowTitle(_translate("Room1", "Parents Room", None))
self.label.setText(_translate("Room1", "Welcome !", None))
self.label_2.setText(_translate("Room1", "Température:", None))
self.label_3.setText(_translate("Room1", "Humidité:", None))
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
Room1 = QtGui.QMainWindow()
ui = Ui_Room1()
ui.setupUi(Room1)
Room1.show()
sys.exit(app.exec_())`
The following must be taken into account:
Reading a temperature sensor takes time, in the case of DHT it consumes 2 seconds, this is not a general disadvantage since the ambient temperature does not vary rapidly.
As the reading task is very time consuming, it should not be executed in the main thread but in a secondary one and send the information through signals.
import time
import threading
import Adafruit_DHT
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
try:
_encoding = QtGui.QApplication.UnicodeUTF8
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig)
class Ui_Room1(object):
def setupUi(self, Room1):
Room1.setObjectName(_fromUtf8("Room1"))
Room1.resize(674, 422)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(Room1.sizePolicy().hasHeightForWidth())
Room1.setSizePolicy(sizePolicy)
Room1.setMouseTracking(False)
Room1.setStyleSheet(
_fromUtf8("image: url(:/gradient1/Images/gradient1.png);\n" "\n" "")
)
self.centralwidget = QtGui.QWidget(Room1)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.centralwidget.sizePolicy().hasHeightForWidth()
)
self.centralwidget.setSizePolicy(sizePolicy)
self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
self.graphicsView = QtGui.QGraphicsView(self.centralwidget)
self.graphicsView.setGeometry(QtCore.QRect(610, 30, 41, 41))
self.graphicsView.setStyleSheet(
_fromUtf8(
"background-color: transparent;\n"
"background-image: url(:/gradient1/Images/logout.png);\n"
"background-repeat: no;"
)
)
self.graphicsView.setFrameShape(QtGui.QFrame.NoFrame)
self.graphicsView.setObjectName(_fromUtf8("graphicsView"))
self.label = QtGui.QLabel(self.centralwidget)
self.label.setGeometry(QtCore.QRect(270, 50, 131, 31))
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.label.sizePolicy().hasHeightForWidth())
self.label.setSizePolicy(sizePolicy)
font = QtGui.QFont()
font.setPointSize(18)
font.setBold(True)
font.setWeight(75)
self.label.setFont(font)
self.label.setStyleSheet(
_fromUtf8(
"image : none;\n" "color: #fff;\n" "background-color: transparent;"
)
)
self.label.setObjectName(_fromUtf8("label"))
self.label_2 = QtGui.QLabel(self.centralwidget)
self.label_2.setGeometry(QtCore.QRect(140, 170, 101, 61))
self.label_2.setStyleSheet(
_fromUtf8("image: none;\n" "color: #fff;\n" "background-color: #347;")
)
self.label_2.setObjectName(_fromUtf8("label_2"))
self.label_3 = QtGui.QLabel(self.centralwidget)
self.label_3.setGeometry(QtCore.QRect(140, 260, 101, 61))
self.label_3.setStyleSheet(
_fromUtf8("image: none;\n" "color: #fff;\n" "background-color: #347;")
)
self.label_3.setObjectName(_fromUtf8("label_3"))
self.label_4 = QtGui.QLabel(self.centralwidget)
self.label_4.setGeometry(QtCore.QRect(300, 170, 101, 61))
self.label_4.setStyleSheet(
_fromUtf8("image: none;\n" "color: #fff;\n" "background-color: #347;")
)
self.label_4.setObjectName(_fromUtf8("label_4"))
self.label_5 = QtGui.QLabel(self.centralwidget)
self.label_5.setGeometry(QtCore.QRect(300, 260, 101, 61))
self.label_5.setStyleSheet(
_fromUtf8("image: none;\n" "color: #fff;\n" "background-color: #347;")
)
self.label_5.setObjectName(_fromUtf8("label_5"))
Room1.setCentralWidget(self.centralwidget)
self.retranslateUi(Room1)
QtCore.QMetaObject.connectSlotsByName(Room1)
def retranslateUi(self, Room1):
Room1.setWindowTitle(_translate("Room1", "Parents Room", None))
self.label.setText(_translate("Room1", "Welcome !", None))
self.label_2.setText(_translate("Room1", "Température:", None))
self.label_3.setText(_translate("Room1", "Humidité:", None))
class Adafruit_DHT_Worker(QtCore.QObject):
valueChanged = QtCore.pyqtSignal(float, float)
def start(self):
threading.Thread(target=self._read, daemon=True).start()
def _read(self):
sensor=11
pin=4
humidity, temperature = Adafruit_DHT.read_retry(sensor, pin)
if humidity is not None and temperature is not None:
self.valueChanged.emit(temperature, humidity)
class Room1(QtGui.QMainWindow, Ui_Room1):
def __init__(self, parent=None):
super().__init__(parent)
self.setupUi(self)
self.dht_worker = Adafruit_DHT_Worker()
self.dht_worker.valueChanged.connect(self.on_value_changed)
self.dht_worker.start()
#QtCore.pyqtSlot(float, float)
def on_value_changed(self, humidity, temperature):
self.label_4.setNum(temperature)
self.label_5.setNum(humidity)
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
w = Room1()
w.show()
sys.exit(app.exec_())

PyQt5 UI crashes while code is running a function

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
....

Python Sqlite3-Program Breaking After Calling execute- SELECT Query

Select query is not executing in python3-sqlite3, instead my program breaks right after that statement. My code is running fine with no errors but whenever i click on radio button (in GUI) which calls a function containing above execute statement ,it breaks.
I'm new to sqlite3 and even python3, I'm working on my first python project which is built using above 2 and Qt designer, after converting my code from qtdesigner i added necessary codes, here's MyCricket.py code:
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import (QApplication, QWidget, QLabel, QPushButton, QRadioButton, QFrame, QMessageBox)
from DialogBox2 import Ui_Dialog
from PyQt5.QtCore import pyqtSlot, QRect
class Ui_MainWindow(object):
def setupUi(self,MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(730, 562)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.label = QtWidgets.QLabel(self.centralwidget)
self.label.setGeometry(QtCore.QRect(20, 30, 101, 21))
font = QtGui.QFont()
font.setPointSize(9)
self.label.setFont(font)
self.label.setObjectName("label")
self.horizontalLayoutWidget = QtWidgets.QWidget(self.centralwidget)
self.horizontalLayoutWidget.setGeometry(QtCore.QRect(20, 60, 681, 61))
self.horizontalLayoutWidget.setObjectName("horizontalLayoutWidget")
self.horizontalLayout = QtWidgets.QHBoxLayout(self.horizontalLayoutWidget)
self.horizontalLayout.setContentsMargins(0, 0, 0, 0)
self.horizontalLayout.setObjectName("horizontalLayout")
self.label_8 = QtWidgets.QLabel(self.horizontalLayoutWidget)
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(9)
font.setBold(True)
font.setWeight(75)
self.label_8.setFont(font)
self.label_8.setObjectName("label_8")
self.horizontalLayout.addWidget(self.label_8)
self.l1 = QtWidgets.QLabel(self.horizontalLayoutWidget)
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(10)
font.setBold(True)
font.setWeight(75)
self.l1.setFont(font)
self.l1.setObjectName("l1")
self.horizontalLayout.addWidget(self.l1)
self.label_9 = QtWidgets.QLabel(self.horizontalLayoutWidget)
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(9)
font.setBold(True)
font.setWeight(75)
self.label_9.setFont(font)
self.label_9.setObjectName("label_9")
self.horizontalLayout.addWidget(self.label_9)
self.l2 = QtWidgets.QLabel(self.horizontalLayoutWidget)
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(10)
font.setBold(True)
font.setWeight(75)
self.l2.setFont(font)
self.l2.setObjectName("l2")
self.horizontalLayout.addWidget(self.l2)
self.label_5 = QtWidgets.QLabel(self.horizontalLayoutWidget)
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(9)
font.setBold(True)
font.setWeight(75)
self.label_5.setFont(font)
self.label_5.setObjectName("label_5")
self.horizontalLayout.addWidget(self.label_5)
self.l3 = QtWidgets.QLabel(self.horizontalLayoutWidget)
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(10)
font.setBold(True)
font.setWeight(75)
self.l3.setFont(font)
self.l3.setObjectName("l3")
self.horizontalLayout.addWidget(self.l3)
self.label_3 = QtWidgets.QLabel(self.horizontalLayoutWidget)
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(9)
font.setBold(True)
font.setWeight(75)
self.label_3.setFont(font)
self.label_3.setObjectName("label_3")
self.horizontalLayout.addWidget(self.label_3)
self.l4 = QtWidgets.QLabel(self.horizontalLayoutWidget)
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(10)
font.setBold(True)
font.setWeight(75)
self.l4.setFont(font)
self.l4.setObjectName("l4")
self.horizontalLayout.addWidget(self.l4)
self.horizontalLayoutWidget_2 = QtWidgets.QWidget(self.centralwidget)
self.horizontalLayoutWidget_2.setGeometry(QtCore.QRect(20, 130, 681, 51))
self.horizontalLayoutWidget_2.setObjectName("horizontalLayoutWidget_2")
self.horizontalLayout_2 = QtWidgets.QHBoxLayout(self.horizontalLayoutWidget_2)
self.horizontalLayout_2.setContentsMargins(0, 0, 0, 0)
self.horizontalLayout_2.setObjectName("horizontalLayout_2")
self.label_13 = QtWidgets.QLabel(self.horizontalLayoutWidget_2)
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(8)
font.setBold(True)
font.setWeight(75)
self.label_13.setFont(font)
self.label_13.setObjectName("label_13")
self.horizontalLayout_2.addWidget(self.label_13)
self.l5 = QtWidgets.QLabel(self.horizontalLayoutWidget_2)
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(9)
font.setBold(True)
font.setWeight(75)
self.l5.setFont(font)
self.l5.setObjectName("l5")
self.horizontalLayout_2.addWidget(self.l5)
spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Minimum)
self.horizontalLayout_2.addItem(spacerItem)
self.label_11 = QtWidgets.QLabel(self.horizontalLayoutWidget_2)
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(8)
font.setBold(True)
font.setWeight(75)
self.label_11.setFont(font)
self.label_11.setObjectName("label_11")
self.horizontalLayout_2.addWidget(self.label_11)
self.l6 = QtWidgets.QLabel(self.horizontalLayoutWidget_2)
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(9)
font.setBold(True)
font.setWeight(75)
self.l6.setFont(font)
self.l6.setObjectName("l6")
self.horizontalLayout_2.addWidget(self.l6)
spacerItem1 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Minimum)
self.horizontalLayout_2.addItem(spacerItem1)
self.listW1 = QtWidgets.QListWidget(self.centralwidget)
self.listW1.setGeometry(QtCore.QRect(30, 230, 261, 271))
font = QtGui.QFont()
font.setFamily("Arial")
font.setBold(True)
font.setWeight(75)
self.listW1.setFont(font)
self.listW1.setObjectName("listW1")
item = QtWidgets.QListWidgetItem()
self.listW2 = QtWidgets.QListWidget(self.centralwidget)
self.listW2.setGeometry(QtCore.QRect(350, 230, 281, 271))
font = QtGui.QFont()
font.setFamily("Arial")
font.setBold(True)
font.setWeight(75)
self.listW2.setFont(font)
self.listW2.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAsNeeded)
self.listW2.setObjectName("listW2")
self.horizontalLayoutWidget_3 = QtWidgets.QWidget(self.centralwidget)
self.horizontalLayoutWidget_3.setGeometry(QtCore.QRect(30, 190, 261, 51))
self.horizontalLayoutWidget_3.setObjectName("horizontalLayoutWidget_3")
self.horizontalLayout_3 = QtWidgets.QHBoxLayout(self.horizontalLayoutWidget_3)
self.horizontalLayout_3.setContentsMargins(0, 0, 0, 0)
self.horizontalLayout_3.setObjectName("horizontalLayout_3")
self.rb1 = QtWidgets.QRadioButton(self.horizontalLayoutWidget_3)
self.rb1.setObjectName("rb1")
self.horizontalLayout_3.addWidget(self.rb1)
self.rb2 = QtWidgets.QRadioButton(self.horizontalLayoutWidget_3)
self.rb2.setObjectName("rb2")
self.horizontalLayout_3.addWidget(self.rb2)
self.rb3 = QtWidgets.QRadioButton(self.horizontalLayoutWidget_3)
self.rb3.setObjectName("rb3")
self.horizontalLayout_3.addWidget(self.rb3)
self.rb4 = QtWidgets.QRadioButton(self.horizontalLayoutWidget_3)
self.rb4.setObjectName("rb4")
self.horizontalLayout_3.addWidget(self.rb4)
self.horizontalLayoutWidget_4 = QtWidgets.QWidget(self.centralwidget)
self.horizontalLayoutWidget_4.setGeometry(QtCore.QRect(350, 190, 281, 51))
self.horizontalLayoutWidget_4.setObjectName("horizontalLayoutWidget_4")
self.horizontalLayout_4 = QtWidgets.QHBoxLayout(self.horizontalLayoutWidget_4)
self.horizontalLayout_4.setContentsMargins(0, 0, 0, 0)
self.horizontalLayout_4.setObjectName("horizontalLayout_4")
spacerItem2 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Minimum)
self.horizontalLayout_4.addItem(spacerItem2)
self.label_14 = QtWidgets.QLabel(self.horizontalLayoutWidget_4)
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
self.label_14.setFont(font)
self.label_14.setObjectName("label_14")
self.horizontalLayout_4.addWidget(self.label_14)
self.l7 = QtWidgets.QLabel(self.horizontalLayoutWidget_4)
self.l7.setObjectName("l7")
self.horizontalLayout_4.addWidget(self.l7)
spacerItem3 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Minimum)
self.horizontalLayout_4.addItem(spacerItem3)
self.label_16 = QtWidgets.QLabel(self.centralwidget)
self.label_16.setGeometry(QtCore.QRect(310, 320, 21, 41))
font = QtGui.QFont()
font.setPointSize(16)
font.setBold(False)
font.setWeight(50)
self.label_16.setFont(font)
self.label_16.setObjectName("label_16")
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 730, 21))
self.menubar.setObjectName("menubar")
self.menuManage_Teams = QtWidgets.QMenu(self.menubar)
self.menuManage_Teams.setObjectName("menuManage_Teams")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.actionNEW_Team = QtWidgets.QAction(MainWindow)
self.actionNEW_Team.setObjectName("actionNEW_Team")
self.actionOPEN_Team = QtWidgets.QAction(MainWindow)
self.actionOPEN_Team.setObjectName("actionOPEN_Team")
self.actionSAVE_Team = QtWidgets.QAction(MainWindow)
self.actionSAVE_Team.setObjectName("actionSAVE_Team")
self.actionEVALUATE_Team = QtWidgets.QAction(MainWindow)
self.actionEVALUATE_Team.setObjectName("actionEVALUATE_Team")
#self.actionEVALUATE_Team.triggered.connect(self.OpenWindow)
self.menuManage_Teams.addAction(self.actionNEW_Team)
self.menuManage_Teams.addSeparator()
self.menuManage_Teams.addAction(self.actionOPEN_Team)
self.menuManage_Teams.addSeparator()
self.menuManage_Teams.addAction(self.actionSAVE_Team)
self.menuManage_Teams.addSeparator()
self.menuManage_Teams.addAction(self.actionEVALUATE_Team)
self.menubar.addAction(self.menuManage_Teams.menuAction())
#self.listW1.itemDoubleClicked.connect(self.removelist1)
#self.listW2.itemDoubleClicked.connect(self.removelist2)
self.rb1.clicked.connect(self.fillList)
self.rb2.clicked.connect(self.fillList)
self.rb3.clicked.connect(self.fillList)
self.rb4.clicked.connect(self.fillList)
#self.menuManage_Teams.triggered[QtWidgets.QAction].connect(self.menu)
self.bat=0
self.bwl=0
self.ar=0
self.wk=0
self.avl=1000
self.used=0
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "Fantasy Cricket Game"))
self.label.setText(_translate("MainWindow", "Your Selections"))
self.label_8.setText(_translate("MainWindow", "Batsmen(BAT)"))
self.l1.setText(_translate("MainWindow", "<html><head/><body><p><span style=\" color:#00aa00;\">##</span></p></body></html>"))
self.label_9.setText(_translate("MainWindow", "Bowlers(BOW)"))
self.l2.setText(_translate("MainWindow", "<html><head/><body><p><span style=\" color:#00aa00;\">##</span></p></body></html>"))
self.label_5.setText(_translate("MainWindow", "Allrounders(AR)"))
self.l3.setText(_translate("MainWindow", "<html><head/><body><p><span style=\" color:#00aa00;\">##</span></p></body></html>"))
self.label_3.setText(_translate("MainWindow", "Wicket-keeper(WK)"))
self.l4.setText(_translate("MainWindow", "<html><head/><body><p><span style=\" color:#00aa00;\">##</span></p></body></html>"))
self.label_13.setText(_translate("MainWindow", "Points Available"))
self.l5.setText(_translate("MainWindow", "<html><head/><body><p><span style=\" color:#00aa00;\">####</span></p></body></html>"))
self.label_11.setText(_translate("MainWindow", "Points Used"))
self.l6.setText(_translate("MainWindow", "<html><head/><body><p><span style=\" color:#00aa00;\">####</span></p></body></html>"))
self.rb1.setText(_translate("MainWindow", "BAT"))
self.rb2.setText(_translate("MainWindow", "BOW"))
self.rb3.setText(_translate("MainWindow", "AR"))
self.rb4.setText(_translate("MainWindow", "WK"))
self.label_14.setText(_translate("MainWindow", "Team Name"))
self.l7.setText(_translate("MainWindow", "<html><head/><body><p><span style=\" color:#00aa00;\">Displayed Here</span></p></body></html>"))
self.label_16.setText(_translate("MainWindow", ">"))
self.menuManage_Teams.setTitle(_translate("MainWindow", "Manage Teams"))
self.actionNEW_Team.setText(_translate("MainWindow", "NEW Team"))
self.actionOPEN_Team.setText(_translate("MainWindow", "OPEN Team"))
self.actionSAVE_Team.setText(_translate("MainWindow", "SAVE Team"))
self.actionEVALUATE_Team.setText(_translate("MainWindow", "EVALUATE Team"))
def fillList(self):
curcricket = MyCricket.cursor()
if self.rb1.isChecked(): # Only showing for radiobutton1 code for rest buttons are similar.
print("HELP")
curcricket.execute("SELECT * FROM Stats WHERE Ctg = BAT;") # This is breaking my code, i added 2 print 'help' to check this breaking.
print("HELP")
BT = curcricket.fetchall()
self.listW1.clear()
for i in range(len(BT)):
item1 = QtWidgets.QListWidgetItem(BT[i][0])
font = QtGui.QFont()
font.setFamily("Comic Sans MS")
font.setPointSize(10)
font.setBold(True)
font.setWeight(75)
item1.setFont(font)
self.listW1.addItem(item1)
curcricket.close()
if __name__ == "__main__":
import sqlite3
MyCricket=sqlite3.connect('MyCricket.db')
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
My application contains Qradiobuttons(BAT,BWL,AR,WK) and QlistWidgets
Whenever radio buttons are clicked i want my list widget to be filled with my Stats Table (only column 1 i.e "Player"(player-name) of particular Category column 7 i.e "Ctg" (BAT,BWL..) ) of database MyCricket.db. Im stuck with this problem and im not able to proceed futher. I wasted a lot of time searching over internet but didnt find a soln to this,I'm still researching so if anyone has the answer, please let me know.

Resources