I'm programming a simple csv handler that will just look at two columns using python 3.7.2 and pyqt5. It will have a desired number of rows and all of them needs to be filled for my program to work. But when I run my loops only 11 out of 20 cells get filled. When I decrease the row count to 10 this ratio is 6/10 and for 6 this is 4/6. I can't find why this occurs.
Here is the loop that sets the headers firstly.
x = 0
while x<total_rows:
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setVerticalHeaderItem(x, item)
x+=1
This is the loop that fills the first column with zeros.
x = 0
while x<total_rows:
print(x)
self.tableWidget.setItem(0,x, QtWidgets.QTableWidgetItem("0"))
x+=1
And this is the loop that fills the second column with zeros.
x = 0
while x<total_rows:
print(x)
self.tableWidget.setItem(1,x, QtWidgets.QTableWidgetItem("0"))
x+=1
For other details that you may need when you are solving my problems here is the whole code. (I have no file sharing platforms available right now. Please accept my apologies for sharing the whole code in text.)
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'database.ui'
#
# Created by: PyQt5 UI code generator 5.11.3
#
# WARNING! All changes made in this file will be lost!
import os
from pandas import DataFrame, read_csv
import pandas as pd
from datetime import datetime
from PyQt5 import QtCore, QtGui, QtWidgets
total_rows = 20
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(551, 602)
#Layout
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.verticalLayout = QtWidgets.QVBoxLayout(self.centralwidget)
self.verticalLayout.setContentsMargins(0, 0, 0, 0)
self.verticalLayout.setSpacing(0)
self.verticalLayout.setObjectName("verticalLayout")
self.widget = QtWidgets.QWidget(self.centralwidget)
self.widget.setMaximumSize(QtCore.QSize(16777215, 70))
self.widget.setStyleSheet("background-color: black;")
self.widget.setObjectName("widget")
self.horizontalLayout = QtWidgets.QHBoxLayout(self.widget)
self.horizontalLayout.setObjectName("horizontalLayout")
self.label = QtWidgets.QLabel(self.widget)
self.label.setStyleSheet("color: white;\nfont-size: 36px;")
self.label.setObjectName("label")
self.horizontalLayout.addWidget(self.label)
spacerItem = QtWidgets.QSpacerItem(337, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
self.horizontalLayout.addItem(spacerItem)
self.verticalLayout.addWidget(self.widget)
self.widget_2 = QtWidgets.QWidget(self.centralwidget)
self.widget_2.setStyleSheet("background-color: #777;")
self.widget_2.setObjectName("widget_2")
self.verticalLayout_2 = QtWidgets.QVBoxLayout(self.widget_2)
self.verticalLayout_2.setObjectName("verticalLayout_2")
self.widget_3 = QtWidgets.QWidget(self.widget_2)
self.widget_3.setStyleSheet("background-color: #556;")
self.widget_3.setObjectName("widget_3")
self.verticalLayout_3 = QtWidgets.QVBoxLayout(self.widget_3)
self.verticalLayout_3.setContentsMargins(0, 0, 0, 0)
self.verticalLayout_3.setSpacing(0)
self.verticalLayout_3.setObjectName("verticalLayout_3")
self.widget_5 = QtWidgets.QWidget(self.widget_3)
self.widget_5.setStyleSheet("background-color:white;")
self.widget_5.setObjectName("widget_5")
self.horizontalLayout_2 = QtWidgets.QHBoxLayout(self.widget_5)
self.horizontalLayout_2.setObjectName("horizontalLayout_2")
#TableWidget
self.tableWidget = QtWidgets.QTableWidget(self.widget_5)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.tableWidget.sizePolicy().hasHeightForWidth())
self.tableWidget.setSizePolicy(sizePolicy)
self.tableWidget.setStyleSheet("background-color: #eee;")
self.tableWidget.setObjectName("tableWidget")
self.tableWidget.setColumnCount(2)
self.tableWidget.setRowCount(total_rows)
x = 0
while x<total_rows:
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setVerticalHeaderItem(x, item)
x+=1
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setHorizontalHeaderItem(0, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setHorizontalHeaderItem(1, item)
self.horizontalLayout_2.addWidget(self.tableWidget)
#CalendarWidget
self.calendarWidget = QtWidgets.QCalendarWidget(self.widget_5)
self.calendarWidget.setStyleSheet("color:black;")
self.calendarWidget.setObjectName("calendarWidget")
self.horizontalLayout_2.addWidget(self.calendarWidget)
self.verticalLayout_3.addWidget(self.widget_5)
self.widget_4 = QtWidgets.QWidget(self.widget_3)
self.widget_4.setStyleSheet("background-color: white;")
self.widget_4.setObjectName("widget_4")
self.verticalLayout_5 = QtWidgets.QVBoxLayout(self.widget_4)
self.verticalLayout_5.setObjectName("verticalLayout_5")
self.widget_8 = QtWidgets.QWidget(self.widget_4)
self.widget_8.setObjectName("widget_8")
self.verticalLayout_5.addWidget(self.widget_8)
self.widget_9 = QtWidgets.QWidget(self.widget_4)
self.widget_9.setObjectName("widget_9")
self.horizontalLayout_6 = QtWidgets.QHBoxLayout(self.widget_9)
self.horizontalLayout_6.setObjectName("horizontalLayout_6")
spacerItem1 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
self.horizontalLayout_6.addItem(spacerItem1)
#PushButton
self.pushButton = QtWidgets.QPushButton(self.widget_9)
self.pushButton.setStyleSheet("background-color: black;\ncolor: white;")
self.pushButton.setObjectName("pushButton")
self.horizontalLayout_6.addWidget(self.pushButton)
spacerItem2 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
self.horizontalLayout_6.addItem(spacerItem2)
self.verticalLayout_5.addWidget(self.widget_9)
self.verticalLayout_3.addWidget(self.widget_4)
self.verticalLayout_2.addWidget(self.widget_3)
self.verticalWidget = QtWidgets.QWidget(self.widget_2)
self.verticalWidget.setStyleSheet("background-color: white;")
self.verticalWidget.setObjectName("verticalWidget")
self.verticalLayout_4 = QtWidgets.QVBoxLayout(self.verticalWidget)
self.verticalLayout_4.setObjectName("verticalLayout_4")
self.widget_7 = QtWidgets.QWidget(self.verticalWidget)
self.widget_7.setObjectName("widget_7")
self.horizontalLayout_4 = QtWidgets.QHBoxLayout(self.widget_7)
self.horizontalLayout_4.setObjectName("horizontalLayout_4")
#ListWidget
self.listWidget = QtWidgets.QListWidget(self.widget_7)
self.listWidget.setStyleSheet("background-color:#eee;")
self.listWidget.setObjectName("listWidget")
#Get files and insert into list widget
files = os.listdir("files")
for index, value in enumerate(files):
item = QtWidgets.QListWidgetItem(value)
self.listWidget.addItem(item)
self.horizontalLayout_4.addWidget(self.listWidget)
spacerItem3 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
self.horizontalLayout_4.addItem(spacerItem3)
self.verticalLayout_4.addWidget(self.widget_7)
self.widget_6 = QtWidgets.QWidget(self.verticalWidget)
self.widget_6.setObjectName("widget_6")
self.horizontalLayout_3 = QtWidgets.QHBoxLayout(self.widget_6)
self.horizontalLayout_3.setObjectName("horizontalLayout_3")
spacerItem4 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
self.horizontalLayout_3.addItem(spacerItem4)
#PushButton2
self.pushButton_2 = QtWidgets.QPushButton(self.widget_6)
self.pushButton_2.setStyleSheet("background-color:black;\ncolor:white;")
self.pushButton_2.setObjectName("pushButton_2")
self.horizontalLayout_3.addWidget(self.pushButton_2)
spacerItem5 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
self.horizontalLayout_3.addItem(spacerItem5)
self.verticalLayout_4.addWidget(self.widget_6)
self.verticalLayout_2.addWidget(self.verticalWidget)
self.verticalLayout.addWidget(self.widget_2)
MainWindow.setCentralWidget(self.centralwidget)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def save_file(self):
#Takvim değerini al
current_date = self.calendarWidget.selectedDate()
current_date_text = current_date.toPyDate().strftime("%d%b%y")
#Table'daki değerleri al
allRows = self.tableWidget.rowCount()
#Pandas table için listeleri oluştur
headers = []
items = []
for row in range(0,allRows):
print(row)
item = self.tableWidget.item(row,1).text()
items.append(item)
item = self.tableWidget.item(row,0).text()
headers.append(item)
#dataset oluştur
data_set = list(zip(headers,items))
#dataframe oluştur
data_frame = pd.DataFrame(data = data_set)
#csv dosyası oluştur
data_frame.to_csv("files/" + current_date_text + ".csv", index = False)
#listview güncelle
files = os.listdir("files")
print(files)
for index, value in enumerate(files):
item = QtWidgets.QListWidgetItem(value)
self.listWidget.addItem(item)
item = self.listWidget.item(index)
item.setText(value)
def open_file(self):
#dosya ismini al
selected_file = self.listWidget.currentItem().text()
#csv dosyasını aç dataframe oluştur
data_frame = pd.read_csv("files/" + selected_file)
items = data_frame["0"].values.tolist()
items = data_frame["1"].values.tolist()
print(items)
for row in range(0,total_rows):
header = row
item = self.tableWidget.setItem(0,row, QtWidgets.QTableWidgetItem(str(items[row])))
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
#Set TableWidget
self.label.setText(_translate("MainWindow", "Defter"))
item = self.tableWidget.horizontalHeaderItem(0)
item.setText(_translate("MainWindow", "Isim"))
item = self.tableWidget.horizontalHeaderItem(1)
item.setText(_translate("MainWindow", "Miktar"))
x = 0
while x<total_rows:
print(x)
self.tableWidget.setItem(0,x, QtWidgets.QTableWidgetItem("0"))
x+=1
x = 0
while x<total_rows:
print(x)
self.tableWidget.setItem(1,x, QtWidgets.QTableWidgetItem("0"))
x+=1
self.pushButton.setText(_translate("MainWindow", "Kaydet"))
self.pushButton.clicked.connect(self.save_file)
__sortingEnabled = self.listWidget.isSortingEnabled()
self.listWidget.setSortingEnabled(False)
files = os.listdir("files")
for index, value in enumerate(files):
item = self.listWidget.item(index)
item.setText(value)
self.listWidget.setSortingEnabled(__sortingEnabled)
self.pushButton_2.setText(_translate("MainWindow", "Dosyayı aç"))
self.pushButton_2.clicked.connect(self.open_file)
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 put the print statements if my loops were just wrong. I checked and all loops run 20 times (As the x values reach 19 everytime).
Edit: It seems like double-digits are the problem.But this syntax is surely true according to the documentation.
self.tableWidget.setItem(1,10, QtWidgets.QTableWidgetItem("0"))
You changed rows with columns
# ...
x = 0
while x < total_rows:
# --- self.tableWidget.setItem(0, x, QtWidgets.QTableWidgetItem("0"))
self.tableWidget.setItem(x, 0, QtWidgets.QTableWidgetItem("0")) # +++
x += 1
x = 0
while x<total_rows:
# --- self.tableWidget.setItem(1,x, QtWidgets.QTableWidgetItem("0"))
self.tableWidget.setItem(x, 1, QtWidgets.QTableWidgetItem("0")) # +++
x += 1
# ...
Related
i have a main code that runs a main UI window, from the main UI window im passing to other window, i tried to implement a back button but for some reason it works only when im in debug mode.
main UI window:
from PyQt5 import QtCore, QtGui, QtWidgets
import UI.plantManagment as plantManagment
class Ui_MainWindow(object):
def __init__(self,MainWindow,loadedgreenhouses) -> None:
self.MainWindow=MainWindow
self.loadedgreenhouses=loadedgreenhouses
def setupUi(self):
self.MainWindow.setObjectName("MainWindow")
self.MainWindow.resize(480, 480)
self.MainWindow.setMinimumSize(QtCore.QSize(480, 480))
self.MainWindow.setMaximumSize(QtCore.QSize(480, 480))
self.MainWindow.setTabletTracking(False)
self.MainWindow.setContextMenuPolicy(QtCore.Qt.NoContextMenu)
self.MainWindow.setAnimated(True)
self.MainWindow.setDocumentMode(False)
self.MainWindow.setTabShape(QtWidgets.QTabWidget.Rounded)
self.centralwidget = QtWidgets.QWidget(self.MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.verticalLayoutWidget = QtWidgets.QWidget(self.centralwidget)
self.verticalLayoutWidget.setGeometry(QtCore.QRect(70, 70, 321, 361))
self.verticalLayoutWidget.setObjectName("verticalLayoutWidget")
self.verticalLayout = QtWidgets.QVBoxLayout(self.verticalLayoutWidget)
self.verticalLayout.setContentsMargins(0, 0, 0, 0)
self.verticalLayout.setObjectName("verticalLayout")
spacerItem = QtWidgets.QSpacerItem(20, 40, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)
self.verticalLayout.addItem(spacerItem)
self.btn_managePlants = QtWidgets.QPushButton(self.verticalLayoutWidget)
self.btn_managePlants.setMinimumSize(QtCore.QSize(0, 80))
font = QtGui.QFont()
font.setPointSize(24)
self.btn_managePlants.setFont(font)
self.btn_managePlants.setObjectName("btn_managePlants")
self.verticalLayout.addWidget(self.btn_managePlants)
self.btn_managePlants.clicked.connect(self.loadPalntsUI)
spacerItem1 = QtWidgets.QSpacerItem(20, 40, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)
self.verticalLayout.addItem(spacerItem1)
self.btn_manageGreenHouses = QtWidgets.QPushButton(self.verticalLayoutWidget)
self.btn_manageGreenHouses.setMinimumSize(QtCore.QSize(0, 80))
font = QtGui.QFont()
font.setPointSize(24)
self.btn_manageGreenHouses.setFont(font)
self.btn_manageGreenHouses.setObjectName("btn_manageGreenHouses")
self.verticalLayout.addWidget(self.btn_manageGreenHouses)
spacerItem2 = QtWidgets.QSpacerItem(20, 40, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)
self.verticalLayout.addItem(spacerItem2)
self.btn_harvestAll = QtWidgets.QPushButton(self.verticalLayoutWidget)
self.btn_harvestAll.setMinimumSize(QtCore.QSize(0, 80))
font = QtGui.QFont()
font.setPointSize(24)
self.btn_harvestAll.setFont(font)
self.btn_harvestAll.setCheckable(False)
self.btn_harvestAll.setChecked(False)
self.btn_harvestAll.setObjectName("btn_harvestAll")
self.verticalLayout.addWidget(self.btn_harvestAll)
spacerItem3 = QtWidgets.QSpacerItem(20, 40, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)
self.verticalLayout.addItem(spacerItem3)
self.lable_harvestableNum = QtWidgets.QLabel(self.centralwidget)
self.lable_harvestableNum.setGeometry(QtCore.QRect(70, 20, 321, 41))
font = QtGui.QFont()
font.setPointSize(18)
font.setBold(False)
font.setWeight(50)
font.setStrikeOut(False)
font.setKerning(False)
self.lable_harvestableNum.setFont(font)
self.lable_harvestableNum.setLayoutDirection(QtCore.Qt.LeftToRight)
self.lable_harvestableNum.setScaledContents(False)
self.lable_harvestableNum.setAlignment(QtCore.Qt.AlignCenter)
self.lable_harvestableNum.setWordWrap(False)
self.lable_harvestableNum.setIndent(2)
self.lable_harvestableNum.setTextInteractionFlags(QtCore.Qt.LinksAccessibleByMouse)
self.lable_harvestableNum.setObjectName("lable_harvestableNum")
self.MainWindow.setCentralWidget(self.centralwidget)
self.statusbar = QtWidgets.QStatusBar(self.MainWindow)
self.statusbar.setObjectName("statusbar")
self.MainWindow.setStatusBar(self.statusbar)
self.retranslateUi()
QtCore.QMetaObject.connectSlotsByName(self.MainWindow)
def retranslateUi(self):
_translate = QtCore.QCoreApplication.translate
self.MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.btn_managePlants.setText(_translate("MainWindow", "manage plants"))
self.btn_manageGreenHouses.setText(_translate("MainWindow", "manage greenhouses"))
self.btn_harvestAll.setText(_translate("MainWindow", "harvest all"))
self.lable_harvestableNum.setText(_translate("MainWindow", f"plant ready for harvest: {self.calcRadyToHarvest()}"))
def calcRadyToHarvest(self):
cnt=0
for gh in self.loadedgreenhouses:
for pp in gh.palntingPoints:
if pp.harvestPlant():
cnt+=1
return cnt
def loadPalntsUI(self):
ui = plantManagment.Ui_MainWindow(self.MainWindow,self.loadedgreenhouses)
ui.setupUi()
ui.MainWindow.show()
here the event is working as intended when i click on self.btn_managePlants.clicked.connect(self.loadPalntsUI) and it loads me the next window witouth a problem.
the second window (where the button doesn't work):
from time import sleep
from PyQt5 import QtCore, QtGui, QtWidgets
import Plant
import UI.mainWindow as mainWindow
class Ui_MainWindow(object):
def __init__(self,MainWindow,loadedgreenhouses) -> None:
self.MainWindow=MainWindow
self.loadedgreenhouses=loadedgreenhouses
def setupUi(self):
self.MainWindow.setObjectName("MainWindow")
self.MainWindow.setWindowModality(QtCore.Qt.NonModal)
self.MainWindow.setEnabled(True)
self.MainWindow.resize(627, 409)
self.MainWindow.setMinimumSize(QtCore.QSize(627, 409))
self.MainWindow.setMaximumSize(QtCore.QSize(627, 409))
self.MainWindow.setTabShape(QtWidgets.QTabWidget.Rounded)
self.centralwidget = QtWidgets.QWidget(self.MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.verticalLayoutWidget = QtWidgets.QWidget(self.centralwidget)
self.verticalLayoutWidget.setGeometry(QtCore.QRect(20, 20, 591, 361))
self.verticalLayoutWidget.setObjectName("verticalLayoutWidget")
self.verticalLayout = QtWidgets.QVBoxLayout(self.verticalLayoutWidget)
self.verticalLayout.setContentsMargins(0, 0, 0, 0)
self.verticalLayout.setObjectName("verticalLayout")
self.label_plants = QtWidgets.QLabel(self.verticalLayoutWidget)
font = QtGui.QFont()
font.setPointSize(18)
self.label_plants.setFont(font)
self.label_plants.setObjectName("label_plants")
self.verticalLayout.addWidget(self.label_plants)
self.tableWidget = QtWidgets.QTableWidget(self.verticalLayoutWidget)
self.tableWidget.setSelectionMode(QtWidgets.QAbstractItemView.SingleSelection)
self.tableWidget.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)
self.tableWidget.setObjectName("tableWidget")
self.tableWidget.setColumnCount(4)
self.tableWidget.setRowCount(0)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setHorizontalHeaderItem(0, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setHorizontalHeaderItem(1, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setHorizontalHeaderItem(2, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setHorizontalHeaderItem(3, item)
self.tableWidget.horizontalHeader().setStretchLastSection(True)
self.tableWidget.verticalHeader().setVisible(False)
self.tableWidget.verticalHeader().setHighlightSections(False)
self.verticalLayout.addWidget(self.tableWidget)
self.tableWidget.setEditTriggers(QtWidgets.QAbstractItemView.NoEditTriggers) #forbid editing
self.tableWidget.setRowCount(len(Plant.Plant.kindsList)) #len of number of plants
for i,p in enumerate(Plant.Plant.plantsLst): #add to the table
self.tableWidget.setItem(i, 0, QtWidgets.QTableWidgetItem(p.kind))
self.tableWidget.setItem(i, 1, QtWidgets.QTableWidgetItem(str(p.grow_time)))
self.tableWidget.setItem(i, 2, QtWidgets.QTableWidgetItem(str(p.temp_min)))
self.tableWidget.setItem(i, 3, QtWidgets.QTableWidgetItem(str(p.temp_max)))
self.horizontalLayout = QtWidgets.QHBoxLayout()
self.horizontalLayout.setObjectName("horizontalLayout")
self.btn_back = QtWidgets.QPushButton(self.verticalLayoutWidget)
font = QtGui.QFont()
font.setPointSize(20)
self.btn_back.setFont(font)
self.btn_back.setObjectName("btn_back")
self.horizontalLayout.addWidget(self.btn_back)
self.btn_back.clicked.connect(self.backBtn)
self.btn_delete = QtWidgets.QPushButton(self.verticalLayoutWidget)
font = QtGui.QFont()
font.setPointSize(20)
self.btn_delete.setFont(font)
self.btn_delete.setObjectName("btn_delete")
self.horizontalLayout.addWidget(self.btn_delete)
self.btn_addPlant = QtWidgets.QPushButton(self.verticalLayoutWidget)
font = QtGui.QFont()
font.setPointSize(20)
self.btn_addPlant.setFont(font)
self.btn_addPlant.setObjectName("btn_addPlant")
self.horizontalLayout.addWidget(self.btn_addPlant)
self.verticalLayout.addLayout(self.horizontalLayout)
self.MainWindow.setCentralWidget(self.centralwidget)
self.statusbar = QtWidgets.QStatusBar(self.MainWindow)
self.statusbar.setObjectName("statusbar")
self.MainWindow.setStatusBar(self.statusbar)
self.retranslateUi()
QtCore.QMetaObject.connectSlotsByName(self.MainWindow)
def retranslateUi(self):
_translate = QtCore.QCoreApplication.translate
self.MainWindow.setWindowTitle(_translate("MainWindow", "plant managment"))
self.label_plants.setText(_translate("MainWindow", "plants:"))
item = self.tableWidget.horizontalHeaderItem(0)
item.setText(_translate("MainWindow", "kind"))
item = self.tableWidget.horizontalHeaderItem(1)
item.setText(_translate("MainWindow", "grow time"))
item = self.tableWidget.horizontalHeaderItem(2)
item.setText(_translate("MainWindow", "min temperature"))
item = self.tableWidget.horizontalHeaderItem(3)
item.setText(_translate("MainWindow", "max temperature"))
self.btn_back.setText(_translate("MainWindow", "back"))
self.btn_delete.setText(_translate("MainWindow", "delete"))
self.btn_addPlant.setText(_translate("MainWindow", "add plant"))
self.tableWidget.show()
def backBtn(self):
print("the lalala")
ui = mainWindow.Ui_MainWindow(self.MainWindow,self.loadedgreenhouses)
ui.setupUi()
self.MainWindow.show()
the event should be triggered by self.btn_back.clicked.connect(self.backBtn) but as i said it would work only in debug mode.
i tried to self.btn_back.clicked.connect(lambda : self.backBtn()) which did took me back to the main UI window but then none of the buttons in that window worked :|
Hello recently I made app which will I show you below. In pyqt5 I want to save qlistwidget items in txt or in database file but I don't know how to do that and also I want to show automatically saved qlistwidget items in qlistwidget when I will run my app. Also I want to delete selected item from qlistwidget in database and also in qlistwidget Please help me how to do that I have no idea where to start from
I have no idea how to do that
# I am using Pyqt5
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QDialog, QInputDialog, QLineEdit
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
self.MW = MainWindow
MainWindow.setObjectName("MainWindow")
MainWindow.resize(288, 267)
MainWindow.setMinimumSize(QtCore.QSize(270, 114))
MainWindow.setMaximumSize(QtCore.QSize(630, 540))
MainWindow.setBaseSize(QtCore.QSize(285, 260))
MainWindow.setLayoutDirection(QtCore.Qt.LeftToRight)
MainWindow.setStyleSheet("QMainWindow{background-color:#6F2232;}")
MainWindow.setToolButtonStyle(QtCore.Qt.ToolButtonIconOnly)
MainWindow.setDocumentMode(False)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setLayoutDirection(QtCore.Qt.LeftToRight)
self.centralwidget.setStyleSheet("QWidget{background-color:#6F2232;}")
self.centralwidget.setObjectName("centralwidget")
self.gridLayout_2 = QtWidgets.QGridLayout(self.centralwidget)
self.gridLayout_2.setContentsMargins(9, 9, -1, -1)
self.gridLayout_2.setObjectName("gridLayout_2")
self.gridLayout = QtWidgets.QGridLayout()
self.gridLayout.setContentsMargins(0, -1, -1, -1)
self.gridLayout.setObjectName("gridLayout")
self.listWidget = QtWidgets.QListWidget(self.centralwidget)
font = QtGui.QFont()
font.setPointSize(13)
self.listWidget.setFont(font)
self.listWidget.setFocusPolicy(QtCore.Qt.StrongFocus)
self.listWidget.setAutoFillBackground(False)
self.listWidget.setStyleSheet("QListWidget{Background-color:#282828;\n"
"color:#FFFFFF}")
self.listWidget.setFrameShape(QtWidgets.QFrame.StyledPanel)
self.listWidget.setFrameShadow(QtWidgets.QFrame.Sunken)
self.listWidget.setLineWidth(1)
self.listWidget.setModelColumn(0)
self.listWidget.setObjectName("listWidget")
self.gridLayout.addWidget(self.listWidget, 0, 0, 1, 1)
self.gridLayout_2.addLayout(self.gridLayout, 0, 0, 1, 1)
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 288, 21))
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.menubar.sizePolicy().hasHeightForWidth())
self.menubar.setSizePolicy(sizePolicy)
self.menubar.setLayoutDirection(QtCore.Qt.LeftToRight)
self.menubar.setStyleSheet("QMenuBar{background-color:#C3083F;\n"
"color:#FFFFFF}")
self.menubar.setDefaultUp(False)
self.menubar.setNativeMenuBar(True)
self.menubar.setObjectName("menubar")
self.menuFile = QtWidgets.QMenu(self.menubar)
font = QtGui.QFont()
font.setPointSize(9)
font.setBold(True)
font.setWeight(75)
self.menuFile.setFont(font)
self.menuFile.setLayoutDirection(QtCore.Qt.LeftToRight)
self.menuFile.setStyleSheet("background-color:#C3083F;\n"
"color:#FFFFFF;")
self.menuFile.setToolTipsVisible(True)
self.menuFile.setObjectName("menuFile")
MainWindow.setMenuBar(self.menubar)
self.toolBar = QtWidgets.QToolBar(MainWindow)
self.toolBar.setEnabled(True)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Preferred)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.toolBar.sizePolicy().hasHeightForWidth())
self.toolBar.setSizePolicy(sizePolicy)
self.toolBar.setFocusPolicy(QtCore.Qt.StrongFocus)
self.toolBar.setLayoutDirection(QtCore.Qt.LeftToRight)
self.toolBar.setStyleSheet("QToolBar{background-color:#282828;\n"
"border:#282828;\n"
"padding:2px;}\n")
self.toolBar.setMovable(True)
self.toolBar.setAllowedAreas(QtCore.Qt.AllToolBarAreas)
self.toolBar.setOrientation(QtCore.Qt.Vertical)
self.toolBar.setIconSize(QtCore.QSize(25, 39))
self.toolBar.setFloatable(True)
self.toolBar.setObjectName("toolBar")
MainWindow.addToolBar(QtCore.Qt.LeftToolBarArea, self.toolBar)
self.actionAdd = QtWidgets.QAction(MainWindow)
icon = QtGui.QIcon()
icon.addPixmap(QtGui.QPixmap(r"C:\Users\User\Desktop\WORK\test\task\plus.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.actionAdd.setIcon(icon)
self.actionAdd.setShortcutContext(QtCore.Qt.WindowShortcut)
self.actionAdd.setAutoRepeat(True)
self.actionAdd.setVisible(True)
self.actionAdd.setMenuRole(QtWidgets.QAction.TextHeuristicRole)
self.actionAdd.setIconVisibleInMenu(True)
self.actionAdd.setShortcutVisibleInContextMenu(False)
self.actionAdd.setObjectName("actionAdd")
self.actionRemove = QtWidgets.QAction(MainWindow)
icon1 = QtGui.QIcon()
icon1.addPixmap(QtGui.QPixmap(r"C:\Users\User\Desktop\WORK\test\task\minus.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.actionRemove.setIcon(icon1)
self.actionRemove.setAutoRepeat(True)
self.actionRemove.setVisible(True)
self.actionRemove.setIconVisibleInMenu(True)
self.actionRemove.setShortcutVisibleInContextMenu(False)
self.actionRemove.setObjectName("actionRemove")
self.actionUp = QtWidgets.QAction(MainWindow)
icon2 = QtGui.QIcon()
icon2.addPixmap(QtGui.QPixmap(r"C:\Users\User\Desktop\WORK\test\task\up-arrow (1).png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.actionUp.setIcon(icon2)
self.actionUp.setAutoRepeat(True)
self.actionUp.setVisible(True)
self.actionUp.setIconVisibleInMenu(True)
self.actionUp.setShortcutVisibleInContextMenu(False)
self.actionUp.setObjectName("actionUp")
self.actionDown = QtWidgets.QAction(MainWindow)
icon3 = QtGui.QIcon()
icon3.addPixmap(QtGui.QPixmap(r"C:\Users\User\Desktop\WORK\test\task\download.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.actionDown.setIcon(icon3)
self.actionDown.setAutoRepeat(True)
self.actionDown.setVisible(True)
self.actionDown.setIconVisibleInMenu(True)
self.actionDown.setShortcutVisibleInContextMenu(False)
self.actionDown.setObjectName("actionDown")
self.actionSort = QtWidgets.QAction(MainWindow)
icon4 = QtGui.QIcon()
icon4.addPixmap(QtGui.QPixmap(r"C:\Users\User\Desktop\WORK\test\task\sort (1).png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.actionSort.setIcon(icon4)
self.actionSort.setAutoRepeat(True)
self.actionSort.setVisible(True)
self.actionSort.setIconVisibleInMenu(True)
self.actionSort.setShortcutVisibleInContextMenu(False)
self.actionSort.setObjectName("actionSort")
self.actionNotepad = QtWidgets.QAction(MainWindow)
icon5 = QtGui.QIcon()
icon5.addPixmap(QtGui.QPixmap(":/task/spiral_bound_booklet_64px.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.actionNotepad.setIcon(icon5)
self.actionNotepad.setObjectName("actionNotepad")
self.menuFile.addAction(self.actionAdd)
self.menuFile.addAction(self.actionRemove)
self.menuFile.addAction(self.actionUp)
self.menuFile.addAction(self.actionDown)
self.menuFile.addAction(self.actionSort)
self.menuFile.addAction(self.actionNotepad)
self.menubar.addAction(self.menuFile.menuAction())
self.toolBar.addAction(self.actionAdd)
self.toolBar.addAction(self.actionRemove)
self.toolBar.addAction(self.actionUp)
self.toolBar.addAction(self.actionDown)
self.toolBar.addAction(self.actionSort)
self.actionAdd.triggered.connect(self.actAdd)
self.actionRemove.triggered.connect(self.actRemove)
self.actionUp.triggered.connect(self.actUp)
self.actionDown.triggered.connect(self.actDown)
self.actionSort.triggered.connect(self.actSort)
#self.actionRemove.triggered.connect(self.actEdit)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.menuFile.setTitle(_translate("MainWindow", "File"))
self.toolBar.setWindowTitle(_translate("MainWindow", "toolBar"))
self.actionAdd.setText(_translate("MainWindow", "Add"))
self.actionRemove.setText(_translate("MainWindow", "Remove"))
self.actionUp.setText(_translate("MainWindow", "Up"))
self.actionDown.setText(_translate("MainWindow", "Down"))
self.actionSort.setText(_translate("MainWindow", "Sort"))
self.actionNotepad.setText(_translate("MainWindow", "Notepad"))
#Here when I will trigger this function I want to add item
#qlistwidget and also add what I wrote in database or txt file
#AUTOMATICALLY. I dont know how to do it please help
def actAdd(self):
row = self.listWidget.currentRow()
QInputDialog.setStyleSheet(self.MW,"QInputDialog{background-color:#C3083F;}")
text, ok = QInputDialog.getText(self.MW,"Add","Add Task")
if ok and text is not None:
self.listWidget.insertItem(row,text)
# Here I want to remove qlistwidget item and remove it from database or in
# txt file too
def actRemove(self):
row = self.listWidget.currentRow()
item = self.listWidget.item(row)
if item is None:
return
else:
item = self.listWidget.takeItem(row)
del item
def actUp(self):
row = self.listWidget.currentRow()
if row >=1:
item = self.listWidget.takeItem(row)
self.listWidget.insertItem(row -1, item)
self.listWidget.setCurrentItem(item)
def actDown(self):
row = self.listWidget.currentRow()
if row < self.listWidget.count() -1:
item = self.listWidget.takeItem(row)
self.listWidget.insertItem(row +1, item)
self.listWidget.setCurrentItem(item)
def actSort(self):
self.listWidget.sortItems()
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_())
Instead of writing the data to disk every time you add or remove an entry in the list you could instead only write the data when the app exists. This can be achieved by subclassing QMainWindow and overriding closeEvent like in the example below. In this example the data is saved to save_file.txt. To automatically read in the saved data when the window is initiated you could override MyMainWindow.__init__, e.g.
# Ui_MainWindow() as before
class MyMainWindow(QtWidgets.QMainWindow):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
self.save_file = 'save_file.txt'
self.read_from_file(self.save_file)
def write_to_file(self, file):
try:
list_widget = self.ui.listWidget
entries = '\n'.join(list_widget.item(ii).text() for ii in range(list_widget.count()))
with open(file, 'w') as fout:
fout.write(entries)
except OSError as err:
print(f"file {file} could not be written")
def read_from_file(self, file):
try:
list_widget = self.ui.listWidget
with open(file, 'r') as fin:
entries = [e.strip() for e in fin.readlines()]
list_widget.insertItems(0, entries)
except OSError as err:
with open(file, 'w'):
pass
def closeEvent(self, event):
should_save = QtWidgets.QMessageBox.question(self, "Save data",
"Should the data be saved?",
defaultButton = QtWidgets.QMessageBox.Yes)
if should_save == QtWidgets.QMessageBox.Yes:
self.write_to_file(self.save_file)
return super().closeEvent(event)
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = MyMainWindow()
MainWindow.show()
sys.exit(app.exec_())
I'm setting a filtering tool in Python 3.7 and I'm using pyqt5. I've created a qtablewidget to store the filters and their complementaries chosen by the user. I'd like to allow the user to combine filters over a data so I added grouped checkboxes in each row to select wanted filters.
Which commands should I use to loop over my qtable to get which checkbox is selected please?
def bindApply(self):
checked_list = []
for i in range(self.tableWidget.rowCount()):
#print(self.tableWidget.rowCount())
if self.tableWidget.item(i, 1).checkState() == QtCore.Qt.Checked:
checked_list.append([i,1])
elif self.tableWidget.item(i, 2).checkState() == QtCore.Qt.Checked:
checked_list.append([i,2])
else:
pass
return(checked_list)
I expect a list containing the indexes of selected rows and columns but my function returns nothing.
Here is a reproducible example:
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(550, 350)
MainWindow.setMinimumSize(QtCore.QSize(550, 350))
MainWindow.setMaximumSize(QtCore.QSize(550, 350))
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.tableWidget = QtWidgets.QTableWidget(self.centralwidget)
self.tableWidget.setGeometry(QtCore.QRect(20, 20, 500, 200))
self.tableWidget.setObjectName("tableWidget")
self.tableWidget.setColumnCount(3)
self.tableWidget.setRowCount(0)
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.pushButton_Save = QtWidgets.QPushButton(self.centralwidget)
self.pushButton_Save.setGeometry(QtCore.QRect(120, 250, 100, 50))
self.pushButton_Save.setMinimumSize(QtCore.QSize(100, 50))
self.pushButton_Save.setMaximumSize(QtCore.QSize(100, 50))
self.pushButton_Save.setObjectName("pushButton_Save")
self.pushButton_Apply = QtWidgets.QPushButton(self.centralwidget)
self.pushButton_Apply.setGeometry(QtCore.QRect(260, 250, 100, 50))
self.pushButton_Apply.setMinimumSize(QtCore.QSize(100, 50))
self.pushButton_Apply.setMaximumSize(QtCore.QSize(100, 50))
self.pushButton_Apply.setObjectName("pushButton_Apply")
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 550, 21))
self.menubar.setObjectName("menubar")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
item = self.tableWidget.horizontalHeaderItem(0)
item.setText(_translate("MainWindow", "Name"))
item = self.tableWidget.horizontalHeaderItem(1)
item.setText(_translate("MainWindow", "Filter"))
item = self.tableWidget.horizontalHeaderItem(2)
item.setText(_translate("MainWindow", "complementary"))
self.pushButton_Save.setText(_translate("MainWindow", "Save"))
self.pushButton_Apply.setText(_translate("MainWindow", "Apply"))
#============================ BINDING ===============================
self.pushButton_Save.clicked.connect(self.bindSave)
self.pushButton_Apply.clicked.connect(self.bindApply)
def bindSave(self):
numRows = self.tableWidget.rowCount()
self.tableWidget.insertRow(numRows)
groupButton = QtWidgets.QButtonGroup(self.tableWidget)
groupButton.setExclusive(True)
it1 = QtWidgets.QTableWidgetItem("filter "+str(numRows))
self.tableWidget.setItem(numRows, 0, it1)
ch_bx1 = QtWidgets.QCheckBox()
groupButton.addButton(ch_bx1)
self.tableWidget.setCellWidget(numRows, 1, ch_bx1)
ch_bx2 = QtWidgets.QCheckBox()
groupButton.addButton(ch_bx2)
self.tableWidget.setCellWidget(numRows, 2, ch_bx2)
def bindApply(self):
checked_list = []
for i in range(self.tableWidget.rowCount()):
#print(self.tableWidget.rowCount())
if self.tableWidget.item(i, 1).checkState() == QtCore.Qt.Checked:
checked_list.append([i,1])
elif self.tableWidget.item(i, 2).checkState() == QtCore.Qt.Checked:
checked_list.append([i,2])
else:
pass
print(checked_list)
if __name__ == "__main__":
import sys
if not QtWidgets.QApplication.instance():
app = QtWidgets.QApplication(sys.argv)
else:
app = QtWidgets.QApplication.instance()
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
You should check the state of the check boxes assigned to the cells, not the state of the item associated with the cell, i.e.
def bindApply(self):
checked_list = []
for i in range(self.tableWidget.rowCount()):
#print(self.tableWidget.rowCount())
if self.tableWidget.cellWidget(i, 1).isChecked():
checked_list.append([i,1])
elif self.tableWidget.cellWidget(i, 2).isChecked():
checked_list.append([i,2])
else:
pass
print(checked_list)
I've got some code that checks which checkboxes a user clicks. Those are then put into an array (aylm). Once the user clicks the book button, a small confirmation window pops up which says are you sure you want to book these rooms. In this confirmation window, I would like the label to say are you sure you want to book (aylm)? so that all the rooms and times selected can be seen by the user. I am not sure how to go about this since I'm using one main window which connects all the smaller windows together, which you can see below in the code.
class Ui_DialogBook(QtWidgets.QDialog, Ui_DialogBook):
def __init__(self, parent=None):
super(Ui_DialogBook, self).__init__(parent)
self.setupUi(self)
class Ui_ViewAllRooms(QtWidgets.QMainWindow, Ui_ViewAllRooms):
def __init__(self, parent=None):
super(Ui_ViewAllRooms, self).__init__(parent)
self.setupUi(self)
self.dialogBook = Ui_DialogBook()
self.book_Button.clicked.connect(self.dialogBook.show)
self.book_Button.clicked.connect(self.book_clicked)
#QtCore.pyqtSlot()
def book_clicked(self):
items = []
for i in range(self.tableWidget.rowCount()):
for j in range(self.tableWidget.columnCount()):
item = self.tableWidget.item(i, j)
if item.checkState() == QtCore.Qt.Checked:
items.append(item)
for it in items:
r = it.row()
c = it.column()
v, h = self.tableWidget.horizontalHeaderItem(c).text(), self.tableWidget.verticalHeaderItem(r).text()
self._checked_items.append([h, v])
aylm = (self.checked_items())
aylm_len = len(aylm)
for nm in range (0, aylm_len):
print (aylm[nm])
def checked_items(self):
return self._checked_items
The auto generated code from PyQt designer for the Ui_DialogBook is below:
class Ui_DialogBook(object):
def setupUi(self, DialogBook):
DialogBook.setObjectName("DialogBook")
DialogBook.setMaximumSize(QtCore.QSize(200, 150))
self.invalidLogin_label = QtWidgets.QLabel(DialogBook)
self.invalidLogin_label.setGeometry(QtCore.QRect(10, 10, 181, 71))
self.invalidLogin_label.setAlignment(QtCore.Qt.AlignCenter)
self.invalidLogin_label.setObjectName("invalidLogin_label")
self.no_button = QtWidgets.QPushButton(DialogBook)
self.no_button.setGeometry(QtCore.QRect(110, 100, 75, 23))
self.no_button.setObjectName("no_button")
self.yes_button = QtWidgets.QPushButton(DialogBook)
self.yes_button.setGeometry(QtCore.QRect(20, 100, 75, 23))
self.yes_button.setObjectName("yes_button")
self.retranslateUi(DialogBook)
QtCore.QMetaObject.connectSlotsByName(DialogBook)
def retranslateUi(self, DialogBook):
_translate = QtCore.QCoreApplication.translate
DialogBook.setWindowTitle(_translate("DialogBook", "Dialog"))
self.invalidLogin_label.setText(_translate("DialogBook", "Are you sure you would like \n to book:\n"))
self.no_button.setText(_translate("DialogBook", "No"))
self.yes_button.setText(_translate("DialogBook", "Yes"))
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
DialogBook = QtWidgets.QDialog()
ui = Ui_DialogBook()
ui.setupUi(DialogBook)
DialogBook.show()
sys.exit(app.exec_())
Ui_ViewAllRooms
from PyQt5.QtCore import QDate, QTime, QDateTime, Qt
class Ui_ViewAllRooms(object):
def setupUi(self, ViewAllRooms):
ViewAllRooms.setObjectName("ViewAllRooms")
ViewAllRooms.resize(671, 347)
ViewAllRooms.setMinimumSize(QtCore.QSize(671, 347))
ViewAllRooms.setMaximumSize(QtCore.QSize(671, 347))
self.centralwidget = QtWidgets.QWidget(ViewAllRooms)
self.centralwidget.setObjectName("centralwidget")
self.tableWidget = QtWidgets.QTableWidget(self.centralwidget)
self.tableWidget.setGeometry(QtCore.QRect(10, 100, 651, 181))
self.tableWidget.setObjectName("tableWidget")
self.tableWidget.setColumnCount(6)
self.tableWidget.setRowCount(5)
self.tableWidget.setHorizontalHeaderLabels("P1 P2 P3 P4 P5 P6".split())
self.tableWidget.setVerticalHeaderLabels("C101 C214 C320 F04 E201".split())
for i in range(self.tableWidget.rowCount()):
for j in range(self.tableWidget.columnCount()):
item = QtWidgets.QTableWidgetItem()
item.setFlags(item.flags() | QtCore.Qt.ItemIsUserCheckable)
item.setCheckState(QtCore.Qt.Unchecked)
self.tableWidget.setItem(i, j, item)
self._checked_items = []
self.label = QtWidgets.QLabel(self.centralwidget)
self.label.setGeometry(QtCore.QRect(10, 290, 231, 41))
self.label.setObjectName("label")
self.book_Button = QtWidgets.QPushButton(self.centralwidget)
self.book_Button.setGeometry(QtCore.QRect(300, 290, 75, 23))
self.book_Button.setObjectName("book_Button")
self.backButton = QtWidgets.QPushButton(self.centralwidget)
self.backButton.setGeometry(QtCore.QRect(590, 10, 75, 23))
self.backButton.setObjectName("backButton")
self.login_title = QtWidgets.QLabel(self.centralwidget)
self.login_title.setGeometry(QtCore.QRect(220, 10, 231, 38))
font = QtGui.QFont()
font.setFamily("Gloucester MT Extra Condensed")
font.setPointSize(25)
font.setBold(False)
font.setItalic(False)
font.setUnderline(True)
font.setWeight(50)
self.login_title.setFont(font)
self.login_title.setLayoutDirection(QtCore.Qt.LeftToRight)
self.login_title.setAutoFillBackground(False)
self.login_title.setAlignment(QtCore.Qt.AlignCenter)
self.login_title.setObjectName("login_title")
self.date_label = QtWidgets.QLabel(self.centralwidget)
self.date_label.setGeometry(QtCore.QRect(240, 70, 191, 21))
self.date_label.setAlignment(QtCore.Qt.AlignCenter)
self.date_label.setObjectName("date_label")
self.nextDayButton = QtWidgets.QPushButton(self.centralwidget)
self.nextDayButton.setGeometry(QtCore.QRect(590, 70, 75, 23))
self.nextDayButton.setObjectName("nextDayButton")
ViewAllRooms.setCentralWidget(self.centralwidget)
self.statusbar = QtWidgets.QStatusBar(ViewAllRooms)
self.statusbar.setObjectName("statusbar")
ViewAllRooms.setStatusBar(self.statusbar)
self.retranslateUi(ViewAllRooms)
QtCore.QMetaObject.connectSlotsByName(ViewAllRooms)
def retranslateUi(self, ViewAllRooms):
_translate = QtCore.QCoreApplication.translate
ViewAllRooms.setWindowTitle(_translate("ViewAllRooms", "MainWindow"))
item = self.tableWidget.verticalHeaderItem(0)
item.setText(_translate("ViewAllRooms", "C101"))
item.setToolTip("Hall")
item = self.tableWidget.verticalHeaderItem(1)
item.setText(_translate("ViewAllRooms", "C214"))
item.setToolTip("Study Space")
item = self.tableWidget.verticalHeaderItem(2)
item.setText(_translate("ViewAllRooms", "C320"))
item.setToolTip("Computer")
item = self.tableWidget.verticalHeaderItem(3)
item.setText(_translate("ViewAllRooms", "F04"))
item.setToolTip("Mac Room")
item = self.tableWidget.verticalHeaderItem(4)
item.setText(_translate("ViewAllRooms", "E201"))
item.setToolTip("Computer")
item = self.tableWidget.horizontalHeaderItem(0)
item.setText(_translate("ViewAllRooms", "P1"))
item.setToolTip("8:55")
item = self.tableWidget.horizontalHeaderItem(1)
item.setText(_translate("ViewAllRooms", "P2"))
item.setToolTip("9:55")
item = self.tableWidget.horizontalHeaderItem(2)
item.setText(_translate("ViewAllRooms", "P3"))
item.setToolTip("11:15")
item = self.tableWidget.horizontalHeaderItem(3)
item.setText(_translate("ViewAllRooms", "P4"))
item.setToolTip("12:15")
item = self.tableWidget.horizontalHeaderItem(4)
item.setText(_translate("ViewAllRooms", "P5"))
item.setToolTip("2:00")
item = self.tableWidget.horizontalHeaderItem(5)
item.setText(_translate("ViewAllRooms", "P6"))
item.setToolTip("3:15")
__sortingEnabled = self.tableWidget.isSortingEnabled()
self.tableWidget.setSortingEnabled(False)
self.tableWidget.setSortingEnabled(__sortingEnabled)
self.book_Button.setText(_translate("ViewAllRooms", "Book"))
self.backButton.setText(_translate("ViewAllRooms", "Back"))
self.login_title.setText(_translate("ViewAllRooms", "VIEW ALL ROOMS"))
self.date_label.setText(_translate("ViewAllRooms", "Date:14 January 2019"))
self.label.setText(_translate("ViewAllRooms", "Hover over a room number or period for\n"
"extra information"))
self.nextDayButton.setText(_translate("ViewAllRooms", "Next Day"))
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
ViewAllRooms = QtWidgets.QMainWindow()
ui = Ui_ViewAllRooms()
ui.setupUi(ViewAllRooms)
ViewAllRooms.show()
sys.exit(app.exec_())
View All Rooms GUI
Try it :
from PyQt5 import QtWidgets, QtGui, QtCore
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
class Ui_DialogBook(object):
def setupUi(self, DialogBook):
DialogBook.setObjectName("DialogBook")
DialogBook.setMaximumSize(QtCore.QSize(200, 150))
self.invalidLogin_label = QtWidgets.QLabel(DialogBook)
self.invalidLogin_label.setGeometry(QtCore.QRect(10, 10, 181, 71))
self.invalidLogin_label.setAlignment(QtCore.Qt.AlignCenter)
self.invalidLogin_label.setObjectName("invalidLogin_label")
self.no_button = QtWidgets.QPushButton(DialogBook)
self.no_button.setGeometry(QtCore.QRect(110, 100, 75, 23))
self.no_button.setObjectName("no_button")
self.yes_button = QtWidgets.QPushButton(DialogBook)
self.yes_button.setGeometry(QtCore.QRect(20, 100, 75, 23))
self.yes_button.setObjectName("yes_button")
self.retranslateUi(DialogBook)
QtCore.QMetaObject.connectSlotsByName(DialogBook)
def retranslateUi(self, DialogBook):
_translate = QtCore.QCoreApplication.translate
DialogBook.setWindowTitle(_translate("DialogBook", "Dialog"))
self.invalidLogin_label.setText(_translate("DialogBook", "Are you sure you would like \n to book:\n"))
self.no_button.setText(_translate("DialogBook", "No"))
self.yes_button.setText(_translate("DialogBook", "Yes"))
class DialogBook(QtWidgets.QDialog, Ui_DialogBook):
def __init__(self, parent=None):
super(DialogBook, self).__init__(parent)
self.setupUi(self)
self.listWidget = QListWidget()
self.grid = QGridLayout(self)
self.grid.addWidget(self.invalidLogin_label, 0, 0, 1, 2)
self.grid.addWidget(self.listWidget, 1, 0, 1, 2)
self.grid.addWidget(self.yes_button, 2, 0)
self.grid.addWidget(self.no_button, 2, 1)
class Ui_ViewAllRooms(object):
def setupUi(self, ViewAllRooms):
ViewAllRooms.setObjectName("ViewAllRooms")
ViewAllRooms.resize(671, 347)
ViewAllRooms.setMinimumSize(QtCore.QSize(671, 347))
ViewAllRooms.setMaximumSize(QtCore.QSize(671, 347))
self.centralwidget = QtWidgets.QWidget(ViewAllRooms)
self.centralwidget.setObjectName("centralwidget")
self.tableWidget = QtWidgets.QTableWidget(self.centralwidget)
self.tableWidget.setGeometry(QtCore.QRect(10, 100, 651, 181))
self.tableWidget.setObjectName("tableWidget")
self.tableWidget.setColumnCount(6)
self.tableWidget.setRowCount(5)
self.tableWidget.setHorizontalHeaderLabels("P1 P2 P3 P4 P5 P6".split())
self.tableWidget.setVerticalHeaderLabels("C101 C214 C320 F04 E201".split())
for i in range(self.tableWidget.rowCount()):
for j in range(self.tableWidget.columnCount()):
item = QtWidgets.QTableWidgetItem()
item.setFlags(item.flags() | QtCore.Qt.ItemIsUserCheckable)
item.setCheckState(QtCore.Qt.Unchecked)
self.tableWidget.setItem(i, j, item)
self._checked_items = []
self.label = QtWidgets.QLabel(self.centralwidget)
self.label.setGeometry(QtCore.QRect(10, 290, 231, 41))
self.label.setObjectName("label")
self.book_Button = QtWidgets.QPushButton(self.centralwidget)
self.book_Button.setGeometry(QtCore.QRect(300, 290, 75, 23))
self.book_Button.setObjectName("book_Button")
self.backButton = QtWidgets.QPushButton(self.centralwidget)
self.backButton.setGeometry(QtCore.QRect(590, 10, 75, 23))
self.backButton.setObjectName("backButton")
self.login_title = QtWidgets.QLabel(self.centralwidget)
self.login_title.setGeometry(QtCore.QRect(220, 10, 231, 38))
font = QtGui.QFont()
font.setFamily("Gloucester MT Extra Condensed")
font.setPointSize(25)
font.setBold(False)
font.setItalic(False)
font.setUnderline(True)
font.setWeight(50)
self.login_title.setFont(font)
self.login_title.setLayoutDirection(QtCore.Qt.LeftToRight)
self.login_title.setAutoFillBackground(False)
self.login_title.setAlignment(QtCore.Qt.AlignCenter)
self.login_title.setObjectName("login_title")
self.date_label = QtWidgets.QLabel(self.centralwidget)
self.date_label.setGeometry(QtCore.QRect(240, 70, 191, 21))
self.date_label.setAlignment(QtCore.Qt.AlignCenter)
self.date_label.setObjectName("date_label")
self.nextDayButton = QtWidgets.QPushButton(self.centralwidget)
self.nextDayButton.setGeometry(QtCore.QRect(590, 70, 75, 23))
self.nextDayButton.setObjectName("nextDayButton")
ViewAllRooms.setCentralWidget(self.centralwidget)
self.statusbar = QtWidgets.QStatusBar(ViewAllRooms)
self.statusbar.setObjectName("statusbar")
ViewAllRooms.setStatusBar(self.statusbar)
self.retranslateUi(ViewAllRooms)
QtCore.QMetaObject.connectSlotsByName(ViewAllRooms)
def retranslateUi(self, ViewAllRooms):
_translate = QtCore.QCoreApplication.translate
ViewAllRooms.setWindowTitle(_translate("ViewAllRooms", "MainWindow"))
item = self.tableWidget.verticalHeaderItem(0)
item.setText(_translate("ViewAllRooms", "C101"))
item.setToolTip("Hall")
item = self.tableWidget.verticalHeaderItem(1)
item.setText(_translate("ViewAllRooms", "C214"))
item.setToolTip("Study Space")
item = self.tableWidget.verticalHeaderItem(2)
item.setText(_translate("ViewAllRooms", "C320"))
item.setToolTip("Computer")
item = self.tableWidget.verticalHeaderItem(3)
item.setText(_translate("ViewAllRooms", "F04"))
item.setToolTip("Mac Room")
item = self.tableWidget.verticalHeaderItem(4)
item.setText(_translate("ViewAllRooms", "E201"))
item.setToolTip("Computer")
item = self.tableWidget.horizontalHeaderItem(0)
item.setText(_translate("ViewAllRooms", "P1"))
item.setToolTip("8:55")
item = self.tableWidget.horizontalHeaderItem(1)
item.setText(_translate("ViewAllRooms", "P2"))
item.setToolTip("9:55")
item = self.tableWidget.horizontalHeaderItem(2)
item.setText(_translate("ViewAllRooms", "P3"))
item.setToolTip("11:15")
item = self.tableWidget.horizontalHeaderItem(3)
item.setText(_translate("ViewAllRooms", "P4"))
item.setToolTip("12:15")
item = self.tableWidget.horizontalHeaderItem(4)
item.setText(_translate("ViewAllRooms", "P5"))
item.setToolTip("2:00")
item = self.tableWidget.horizontalHeaderItem(5)
item.setText(_translate("ViewAllRooms", "P6"))
item.setToolTip("3:15")
__sortingEnabled = self.tableWidget.isSortingEnabled()
self.tableWidget.setSortingEnabled(False)
self.tableWidget.setSortingEnabled(__sortingEnabled)
self.book_Button.setText(_translate("ViewAllRooms", "Book"))
self.backButton.setText(_translate("ViewAllRooms", "Back"))
self.login_title.setText(_translate("ViewAllRooms", "VIEW ALL ROOMS"))
self.date_label.setText(_translate("ViewAllRooms", "Date:14 January 2019"))
self.label.setText(_translate("ViewAllRooms", "Hover over a room number or period for\n"
"extra information"))
self.nextDayButton.setText(_translate("ViewAllRooms", "Next Day"))
class ViewAllRooms(QtWidgets.QMainWindow, Ui_ViewAllRooms):
def __init__(self, parent=None):
super(ViewAllRooms, self).__init__(parent)
self.setupUi(self)
self.dialogBook = DialogBook() #Ui_DialogBook() #
# self.book_Button.clicked.connect(self.dialogBook.show)
self.book_Button.clicked.connect(self.book_clicked)
#QtCore.pyqtSlot()
def book_clicked(self):
self._checked_items = []
# items = []
for i in range(self.tableWidget.rowCount()):
for j in range(self.tableWidget.columnCount()):
item = self.tableWidget.item(i, j)
if item.checkState() == QtCore.Qt.Checked:
# items.append(item)
# r = it.row()
# c = it.column()
v = self.tableWidget.horizontalHeaderItem(j).text()
h = self.tableWidget.verticalHeaderItem(i).text()
self._checked_items.append([h, v, self.tableWidget.item(i, j).text()])
self.dialogBook.listWidget.clear()
self.dialogBook.listWidget.addItems([ "{} {} {}".format(h, v, it) for h, v, it in self._checked_items])
self.dialogBook.show()
"""
print("items->", items)
for it in items:
r = it.row()
c = it.column()
v, h = self.tableWidget.horizontalHeaderItem(c).text(), self.tableWidget.verticalHeaderItem(r).text()
print("item---", self.tableWidget.item(r, c).text())
self._checked_items.append([h, v])
aylm = (self.checked_items())
aylm_len = len(aylm)
for nm in range (0, aylm_len):
print (aylm[nm])
def checked_items(self):
return self._checked_items
"""
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
DialogBook = ViewAllRooms()
# DialogBook = QtWidgets.QDialog()
# ui = DialogBook()
# ui.setupUi(DialogBook)
DialogBook.show()
sys.exit(app.exec_())
(Picture 1) - Here is the output of my simple program, supposedly it has 5 dropdown items coming from the database but it only displays 1 data which is the last row of the db that has been read.
Picture 1 -
(Picture 2) - Here is the code, I used for loop and I expect it to loop through it and display every data from db but it only display the last row. Is it wrong syntax or wrong logic?
# Combobox - Subjects
self.cbSubjects = ttk.Combobox(root, width=17, textvariable=self.cbSubjects)
self.cbSubjects.place(x=120, y=60)
# SQL Command
self.conn = cx_Oracle.connect('system/system#127.0.0.1/xe')
self.cursor = self.conn.cursor()
self.cursor.execute("SELECT hr.subject.description FROM hr.subject")
for i in self.cursor:
self.cbSubjects['values'] = (i)
self.cbSubjects.current(0)
self.cursor.close()
self.conn.close()
(Picture 3) - Here is the SQL data that I'd like to display on my Combobox
Picture 3 -
I'm new to Python tkinter. Thank you so much!
Inside the for loop, you are simply overriding the single value you have in your combobox why this line is executed: self.cbSubjects['values'] = (i). The last value you assign to it is the last row returned by the SELECT SQL statement. So this is the explanation of the reason you faced that problem.
For the solution, if you take a look at the documentation which is often your best friend, you can read this:
values Specifies the list of values to display in the drop-down
listbox.
Actually this is a little bit misleading because self.cbSubjects['values'] is rather a tuple, not a list, and as you know tuples are immutable, unlike lists, but still you can overcome this problem by making making i wearing the clothes of a tuple having one single element.
Maybe with code, you will understand the idea better:
#...
for i in self.cursor:
# self.cbSubjects['values'] = (i) , this is bad, change it like this:
self.cbSubjects['values'] = self.cbSubjects['values'] + (i, )
# ... rest of your program
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'delivery.ui'
#
# Created by: PyQt5 UI code generator 5.14.1
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
import sqlite3
conn = sqlite3.connect("spmanager.db")
cursor = conn.cursor()
class Ui_Form(object):
def setupUi(self, Form):
Form.setObjectName("Form")
Form.resize(773, 621)
self.label = QtWidgets.QLabel(Form)
self.label.setGeometry(QtCore.QRect(310, 20, 121, 20))
font = QtGui.QFont()
font.setFamily("Ubuntu Condensed")
font.setPointSize(12)
font.setBold(True)
font.setWeight(75)
self.label.setFont(font)
self.label.setObjectName("label")
self.verticalLayoutWidget = QtWidgets.QWidget(Form)
self.verticalLayoutWidget.setGeometry(QtCore.QRect(50, 210, 701, 331))
self.verticalLayoutWidget.setObjectName("verticalLayoutWidget")
self.verticalLayout = QtWidgets.QVBoxLayout(self.verticalLayoutWidget)
self.verticalLayout.setContentsMargins(0, 0, 0, 0)
self.verticalLayout.setObjectName("verticalLayout")
self.tableWidget = QtWidgets.QTableWidget(self.verticalLayoutWidget)
self.tableWidget.setObjectName("tableWidget")
self.tableWidget.setColumnCount(3)
self.tableWidget.setRowCount(1)
item = QtWidgets.QTableWidgetItem()
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.verticalLayout.addWidget(self.tableWidget)
self.frame_3 = QtWidgets.QFrame(Form)
self.frame_3.setGeometry(QtCore.QRect(40, 550, 331, 80))
self.frame_3.setFrameShape(QtWidgets.QFrame.StyledPanel)
self.frame_3.setFrameShadow(QtWidgets.QFrame.Raised)
self.frame_3.setObjectName("frame_3")
self.label_4 = QtWidgets.QLabel(self.frame_3)
self.label_4.setGeometry(QtCore.QRect(0, 0, 91, 17))
self.label_4.setObjectName("label_4")
self.textEdit = QtWidgets.QTextEdit(self.frame_3)
self.textEdit.setGeometry(QtCore.QRect(10, 19, 291, 61))
self.textEdit.setObjectName("textEdit")
self.layoutWidget = QtWidgets.QWidget(Form)
self.layoutWidget.setGeometry(QtCore.QRect(50, 70, 691, 91))
self.layoutWidget.setObjectName("layoutWidget")
self.gridLayout = QtWidgets.QGridLayout(self.layoutWidget)
self.gridLayout.setContentsMargins(0, 0, 0, 0)
self.gridLayout.setObjectName("gridLayout")
self.frame_2 = QtWidgets.QFrame(self.layoutWidget)
self.frame_2.setFrameShape(QtWidgets.QFrame.StyledPanel)
self.frame_2.setFrameShadow(QtWidgets.QFrame.Raised)
self.frame_2.setObjectName("frame_2")
self.label_3 = QtWidgets.QLabel(self.frame_2)
self.label_3.setGeometry(QtCore.QRect(10, 30, 67, 17))
self.label_3.setObjectName("label_3")
self.dateEdit = QtWidgets.QDateEdit(self.frame_2)
self.dateEdit.setGeometry(QtCore.QRect(70, 20, 151, 41))
self.dateEdit.setObjectName("dateEdit")
self.gridLayout.addWidget(self.frame_2, 0, 1, 1, 1)
self.frame = QtWidgets.QFrame(self.layoutWidget)
self.frame.setFrameShape(QtWidgets.QFrame.StyledPanel)
self.frame.setFrameShadow(QtWidgets.QFrame.Raised)
self.frame.setObjectName("frame")
self.label_2 = QtWidgets.QLabel(self.frame)
self.label_2.setGeometry(QtCore.QRect(20, 30, 71, 21))
self.label_2.setObjectName("label_2")
self.comboBox = QtWidgets.QComboBox(self.frame)
self.comboBox.setGeometry(QtCore.QRect(80, 30, 171, 25))
self.comboBox.setEditable(True)
self.comboBox.setObjectName("comboBox")
self.comboBox.addItem("")
#list1 = ['First Item','Second Item','Third Item']
#self.comboBox.addItems(list1)
self.gridLayout.addWidget(self.frame, 0, 0, 1, 1)
self.frame_4 = QtWidgets.QFrame(Form)
self.frame_4.setGeometry(QtCore.QRect(540, 540, 181, 81))
self.frame_4.setFrameShape(QtWidgets.QFrame.StyledPanel)
self.frame_4.setFrameShadow(QtWidgets.QFrame.Raised)
self.frame_4.setObjectName("frame_4")
self.comboBox_2 = QtWidgets.QComboBox(self.frame_4)
self.comboBox_2.setGeometry(QtCore.QRect(5, 20, 141, 25))
self.comboBox_2.setObjectName("comboBox_2")
self.comboBox_2.addItem("")
self.comboBox_2.addItem("")
self.comboBox_2.addItem("")
self.comboBox_2.addItem("")
self.pushButton = QtWidgets.QPushButton(self.frame_4)
self.pushButton.setGeometry(QtCore.QRect(8, 50, 131, 25))
self.pushButton.setObjectName("pushButton")
self.retranslateUi(Form)
QtCore.QMetaObject.connectSlotsByName(Form)
def customer_names(self):
self.conn = conn
self.cursor = cursor
self.cursor.execute("SELECT customer_name FROM customers ORDER BY customer_name")
self.sql =cursor.fetchall()
customer_names(self)
self.names =[]
for i in self.sql:
self.names.append(i[0])
self.comboBox.addItems(self.names)
def retranslateUi(self, Form):
_translate = QtCore.QCoreApplication.translate
Form.setWindowTitle(_translate("Form", "HI-SPECS INNOVATIVE DELIVERY NOTE"))
self.label.setText(_translate("Form", "DELIVERY NOTE"))
item = self.tableWidget.verticalHeaderItem(0)
item.setText(_translate("Form", "1"))
item = self.tableWidget.horizontalHeaderItem(0)
item.setText(_translate("Form", "Qnty"))
item = self.tableWidget.horizontalHeaderItem(1)
item.setText(_translate("Form", "Item"))
item = self.tableWidget.horizontalHeaderItem(2)
item.setText(_translate("Form", "Description"))
self.label_4.setText(_translate("Form", "Comment"))
self.label_3.setText(_translate("Form", "Date:"))
self.label_2.setText(_translate("Form", "Name:"))
self.comboBox.setItemText(0, _translate("Form", "customer"))
self.comboBox_2.setItemText(0, _translate("Form", "Print & Record"))
self.comboBox_2.setItemText(1, _translate("Form", "Print"))
self.comboBox_2.setItemText(2, _translate("Form", "Record"))
self.comboBox_2.setItemText(3, _translate("Form", "Email"))
self.pushButton.setText(_translate("Form", "Continue"))
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_())