Object not connected when change in combobox - python

Given a MainWindow with a menu (currently not used) and a table with editable data, there are two problems:
when I change the year or the month I get
table.itemChanged.disconnect(MainCalendar.cellChange)
TypeError: 'function' object is not connected
if I edit a cell of the initial table I get
File "/root/PycharmProjects/mre/cal_main.py", line 78, in cellChange
row = item.row()
AttributeError: 'str' object has no attribute 'row'
P.S. the scripts used in stand alone (not inserted in the MainWindow) work correctly
index.py
class MainApp(QMainWindow, StartUi):
def __init__(self):
QMainWindow.__init__(self)
self.setupUi(self)
#######
# Other stuff
#######
def main():
app = QApplication(sys.argv)
window = MainApp()
window.show()
sys.exit(app.exec_())
if __name__ == "__main__":
main()
UI_main.py
class StartUi(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("nothing to read")
MainWindow.setGeometry(170, 100, 500, 300)
MainWindow.setWindowTitle("title")
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.menubar = QtWidgets.QMenuBar(self.centralwidget)
self.menubar.setGeometry(QtCore.QRect(0, 0, 500, 19))
self.menuHours = QtWidgets.QMenu(self.menubar)
self.menuHours.setTitle("Hours")
self.actionGlobal = QtWidgets.QAction(MainWindow)
self.menuHours.addAction(self.actionGlobal)
self.actionGlobal.triggered.connect(self.hGlobal)
self.menubar.addAction(self.menuHours.menuAction())
QtCore.QMetaObject.connectSlotsByName(MainWindow)
MainWindow.setMenuBar(self.menubar)
MainCalendar.calendar(self, MainWindow)
def hGlobal(self):
pass
cal_main.py
class ReadOnlyDelegate(QtWidgets.QStyledItemDelegate):
def createEditor(self, parent, option, index):
return
class MainCalendar():
def calendar(self, MainWindow):
self.allyears = ['2021', '2022', '2023', '2024']
self.number = ['Jan', 'Feb', 'Mar', 'Apr']
self.alldata = [['name1', 'value10', 'value11', 'value12', 'value13'],
['name2', 'value20', 'value21', 'value22', 'value23'],
['name3', 'value30', 'value31', 'value32', 'value33'],
['name4', 'value40', 'value41', 'value42', 'value43']]
self.this_month = strftime("%-m")
self.this_year = strftime("%Y")
self.this_month = '2'
global this_month, this_year
self.table = QtWidgets.QTableWidget(MainWindow)
global daysinmonth
this_year = strftime("%Y")
this_month = strftime("%-m")
self.table.setGeometry(QtCore.QRect(20, 60, 300, 200))
self.table.setColumnCount(7)
self.table.setRowCount(1)
self.table.verticalHeader().hide()
self.table.horizontalHeader().setStretchLastSection(False)
self.table.horizontalHeader().setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents)
self.table.horizontalHeader().setCascadingSectionResizes(True)
self.table.horizontalHeader().setDefaultSectionSize(5)
self.ySel = QtWidgets.QComboBox(MainWindow)
self.ySel.setGeometry(QtCore.QRect(200, 10, 80, 20))
self.ySel.addItems(self.allyears)
self.ySel.setCurrentText(self.this_year)
self.mSel = QtWidgets.QComboBox(MainWindow)
self.mSel.setGeometry(QtCore.QRect(290, 10, 100, 20))
self.mSel.addItems(self.number)
self.mSel.setCurrentText(self.number[int(self.this_month) - 1])
self.btn = QtWidgets.QPushButton(MainWindow)
self.btn.setGeometry(QtCore.QRect(250, 40, 50, 15))
self.btn.setText("Select")
self.btn.clicked.connect(lambda clicked: MainCalendar.calSelect(self, self.table))
i = 0
while i <= 3:
self.table.insertRow(i + 1)
zz = 0
while zz <= 4:
item = self.alldata[i][zz]
cell = QTableWidgetItem(item)
self.table.setItem(i, zz, cell)
zz += 1
i += 1
MainWindow.show()
self.table.itemChanged.connect(lambda clicked: MainCalendar.cellChange(self, item))
def cellChange(self, item):
roww = item.row()
coll = item.column()
print(str(roww) + '---' + str(coll))
val = self.table.item(roww, coll).text()
pass
def calSelect(self, table):
table.itemChanged.disconnect(MainCalendar.cellChange)
foo = 0
pass
def cellChange(self, item):
row = item.row()
col = item.column()
val = self.table.item(row, col).text()
print(val)

Related

Many small tables include in a bigger table

I have to create one or more displayboards that will contain smaller tables as you can see from the photos.
Image with 10 names - unusable:
Image with 6 names - 5 are missing:
The problem is that I can't get either a display board extended in length with a scrollbar or two or more displayboards (it depends on how many names are to be entered). I have tried various systems but in the case of "long displayboard" even varying the values ​in window.setGeometry (QtCore.QRect (0, 0, 980, 620)) I can't get the scrollbar, in the case of more displayboards I just can't manage get nothing.
This is the starting piece of code that I used to get the code to work
from functions import *
from PyQt5 import QtCore, QtWidgets
class SpecialStyledItemDelegate(QtWidgets.QStyledItemDelegate):
def __init__(self, parent=None):
super().__init__(parent)
self._values = dict()
def add_text(self, text, row):
self._values[row] = text
def initStyleOption(self, option, index):
super().initStyleOption(option, index)
row = index.row()
if row in self._values:
option.text = self._values[row]
option.displayAlignment = QtCore.Qt.AlignCenter
class MakeStrip(QtWidgets.QWidget):
def __init__(self, anno, mese):
super().__init__()
self.initUI(anno, mese)
def initUI(self, anno, mese):
self.title = "MAMbo - Strips di '%s' '%s' " % (mese, anno)
self.setWindowTitle(self.title)
self.setGeometry(50, 100, 250, 800)
self.callTable(anno, mese)
self.Close_btn = QtWidgets.QPushButton(self)
self.Close_btn.setGeometry(QtCore.QRect(1000, 570, 70, 20))
self.Close_btn.setStyleSheet("background-color : yellow")
self.Close_btn.setObjectName("Strip_Add_btn")
_translate = QtCore.QCoreApplication.translate
self.Close_btn.setText(_translate("Library_main", "Close"))
self.Close_btn.clicked.connect(self.close)
layout = QtWidgets.QVBoxLayout(self)
layout.addWidget(self.tableWidget)
layout.addWidget(self.Close_btn)
def callTable(self, anno, mese):
anno = "2021"
self.alphamese = "January"
# Create table
self.tableWidget = QtWidgets.QTableWidget()
self.tableWidget.setRowCount(10)
self.tableWidget.setColumnCount(3)
self.special_delegate = SpecialStyledItemDelegate()
self.tableWidget.setItemDelegate(self.special_delegate)
self.special_delegate.add_text("JOE DOE", 0)
self.special_delegate.add_text("January", 1)
h_header = self.tableWidget.horizontalHeader()
h_header.hide()
for i in range(h_header.count()):
h_header.setSectionResizeMode(i, QtWidgets.QHeaderView.ResizeToContents)
v_header = self.tableWidget.verticalHeader()
v_header.hide()
v_header.setDefaultSectionSize(13)
self.tableWidget.setSpan(1, 0, 1, 3)
self.tableWidget.setSpan(0, 0, 1, 3)
for zz in range(1, 10):
dow = "do{}".format(zz)
value = "AAAAAAAA{}".format(zz)
self.tableWidget.setItem(zz + 1, 0, QtWidgets.QTableWidgetItem(str(zz)))
self.tableWidget.setItem(zz + 1, 1, QtWidgets.QTableWidgetItem(dow))
item = QtWidgets.QTableWidgetItem(value)
item.setTextAlignment(QtCore.Qt.AlignCenter)
self.tableWidget.setItem(zz + 1, 2, item)
def close (self):
Functions.error_handler(message="message")
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
anno = "2021"
mese = "January"
ex = MakeStrip(anno, mese)
ex.show()
sys.exit(app.exec_())
Below, the job code
import sys
from PyQt5 import QtWidgets
from PyQt5 import QtCore
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QMainWindow, QApplication, QWidget, QAction, QTableWidget, QTableWidgetItem, QVBoxLayout
from functions import *
from index import *
class SpecialStyledItemDelegate(QtWidgets.QStyledItemDelegate):
def __init__(self, parent=None):
super().__init__(parent)
self._values = dict()
def add_text(self, text, row):
self._values[row] = text
def initStyleOption(self, option, index):
super().initStyleOption(option, index)
row = index.row()
if row in self._values:
option.text = self._values[row]
option.displayAlignment = QtCore.Qt.AlignCenter
class Make_Strip():
def MakeStrip(self, window: QWindow, anno, mese, cursor):
global table
layout = QHBoxLayout()
self.alphamese = Functions.convert_number_month[mese]
cursor = Functions.openDB(self)
query = "SELECT * FROM `alldata` WHERE anno = '%s' AND mese = '%s' " % (anno, mese)
self.cursor.execute(query)
search = self.cursor.fetchall()
#numrows = self.cursor.rowcount()
cnt= 0
x_ax = 10
for row in search:
if cnt == 6: break # This is to have something useful (picture 2)
self.vol_name = row['nome']
self.c_query = "SELECT grp FROM volontari WHERE cognome = '%s'" % (self.vol_name)
self.cursor.execute(self.c_query)
self.grp = self.cursor.fetchall()
for val in self.grp:
self.group = val['grp']
if self.group == 'C':
table = QTableWidget()
table.setGeometry(QtCore.QRect(x_ax, 5, 150, 597))
table.setObjectName("StripTable")
table.setRowCount(33)
table.setColumnCount(3)
self.special_delegate = SpecialStyledItemDelegate()
table.setItemDelegate(self.special_delegate)
h_header = table.horizontalHeader()
h_header.hide()
for i in range(h_header.count()):
h_header.setSectionResizeMode(i, QtWidgets.QHeaderView.ResizeToContents)
v_header = table.verticalHeader()
v_header.hide()
v_header.setDefaultSectionSize(18)
table.setSpan(1, 0, 1, 3)
table.setSpan(0, 0, 1, 3)
zz = 1
self.m_query = "SELECT * FROM `alldata` WHERE anno = '%s' AND mese = '%s' AND nome = '%s'" %(anno, mese, self.vol_name)
self.cursor.execute(self.m_query)
result = self.cursor.fetchall()
self.special_delegate.add_text(self.vol_name, 0)
self.special_delegate.add_text(self.alphamese, 1)
daysinmonth = calendar.monthrange(int(anno), int(mese))[1]
while zz <= daysinmonth:
for inrow in result:
day = 'd' + str(zz)
self.value = inrow[day]
a_date = datetime.date(int(anno), int(mese), zz)
self.dow = a_date.strftime("%a")
self.dow = Functions.convert_en_it[self.dow]
if (self.dow == 'Sun' or self.dow == 'Sat') and (self.value == 'P' or self.value == 'D' or self.value == 'F' or self.value == 'B'):
self.value = Functions.eva_mp1[self.value]
else: self.value = Functions.eva_mp[self.value]
table.setItem(zz+1, 0, QtWidgets.QTableWidgetItem(str(zz)))
table.setItem(zz+1, 1, QtWidgets.QTableWidgetItem(self.dow))
item = QtWidgets.QTableWidgetItem(self.value)
item.setTextAlignment(QtCore.Qt.AlignCenter)
table.setItem(zz+1, 2, item)
zz += 1
#table.show()
cnt = cnt + 1
x_ax = x_ax + 150
layout.addWidget(table)
pippo = 0
window.setGeometry(QtCore.QRect(0, 0, 980, 620))
window.setLayout(layout)
window.show()

How to autorefresh pyqt5 table when the data is updated

I want to add one functionality in my application when update is done then data in pyqt5 table should automatically refreshed with the new data in search results. But when I click the buttom, there is nothing happened.
# -*- coding: utf-8 -*-
from PyQt5 import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
import sys
import logging
import logging.config
import time
class Ui_Control_system(object):
def setupUi(self, Control_system):
Control_system.setObjectName("Control_system")
Control_system.resize(1004, 722)
Control_system.setFixedSize(1004, 722)
Control_system.setWindowIcon(QIcon('images/icon.png'))
Control_system.setStyleSheet("QMainWindow{border-image:url(images/background.jpg)}")
self.centralwidget = QtWidgets.QWidget(Control_system)
self.centralwidget.setObjectName("centralwidget")
#表格显示
self.tableWidget = QtWidgets.QTableWidget(self.centralwidget)
self.tableWidget.setGeometry(QtCore.QRect(130, 170, 752, 245))
self.tableWidget.setRowCount(8)
self.tableWidget.setColumnCount(6)
self.tableWidget.setObjectName("tableWidget")
self.tableWidget.horizontalHeader().setVisible(False)
self.tableWidget.horizontalHeader().setCascadingSectionResizes(False)
self.tableWidget.horizontalHeader().setDefaultSectionSize(125)
self.tableWidget.horizontalHeader().setHighlightSections(True)
self.tableWidget.horizontalHeader().setSortIndicatorShown(False)
self.tableWidget.verticalHeader().setVisible(False)
Control_system.setCentralWidget(self.centralwidget)
self.tableWidget.setAutoFillBackground(True)
self.tableWidget.setItem(0,0,QTableWidgetItem("机器编号"))
self.tableWidget.setItem(0,1,QTableWidgetItem("烟雾值"))
self.tableWidget.setItem(0,2,QTableWidgetItem("火焰值"))
self.tableWidget.setItem(0,3, QTableWidgetItem("温度值"))
self.tableWidget.setItem(0,4, QTableWidgetItem("电流值"))
self.tableWidget.setItem(0,5, QTableWidgetItem("电压值"))
font = QtGui.QFont()
font.setPointSize(15)
font.setBold(True)
self.tableWidget.item(0,0).setFont(font)
self.tableWidget.item(0,1).setFont(font)
self.tableWidget.item(0,2).setFont(font)
self.tableWidget.item(0,3).setFont(font)
self.tableWidget.item(0,4).setFont(font)
self.tableWidget.item(0,5).setFont(font)
self.label = QtWidgets.QLabel(self.centralwidget)
self.label.setGeometry(QtCore.QRect(360, 70, 300, 50))
self.label.setObjectName("label")
self.label.setAutoFillBackground(True)
self.label.setAlignment(Qt.AlignCenter)
self.label.setStyleSheet("border-image:url(images/title.png)")
self.pushButton = QtWidgets.QPushButton(self.centralwidget)
self.pushButton.setGeometry(QtCore.QRect(730, 480, 121, 41))
self.pushButton.setObjectName("pushButton")
self.pushButton.clicked.connect(self.slotStart)
Control_system.setCentralWidget(self.centralwidget)
self.statusbar = QtWidgets.QStatusBar(Control_system)
self.statusbar.setObjectName("statusbar")
Control_system.setStatusBar(self.statusbar)
self.retranslateUi(Control_system)
QtCore.QMetaObject.connectSlotsByName(Control_system)
def retranslateUi(self, Control_system):
_translate = QtCore.QCoreApplication.translate
Control_system.setWindowTitle(_translate("Control_system", "实时监控系统"))
self.pushButton.setText(_translate("Control_system", "开始运行"))
def slotStart(self):
#开始按钮不可点击,线程开始
self.pushButton.setEnabled(False)
self.update_data_thread = UpdateData()
self.update_data_thread.update_data.connect(self.set_btn)
self.update_data_thread.start()
def set_btn(self):
self.pushButton.setEnabled(True)
class UpdateData(QtCore.QThread):#使用qt自己本身的线程
update_data=QtCore.pyqtSignal()#因为这个信号槽要继承于Qobject,不然会发生没有emit,connect函数的报错,括号里面填写的是发射的数据类型
#print(".............")
def __init__(self):
super().__init__()
def run(self):
cnt = 0
while True:
cnt += 1
self.tableWidget.setItem(2,2,QTableWidgetItem(cnt))
self.update_data.emit() # 发射信号
time.sleep(1)
if __name__ == '__main__':
if not QtWidgets.QApplication.instance():
app = QtWidgets.QApplication(sys.argv)
else:
app = QtWidgets.QApplication.instance()
MainWindow = QtWidgets.QMainWindow()
ui = Ui_Control_system()
ui.setupUi(MainWindow) # 将ui实例绘制到窗口实例上​
desktop = QtWidgets.QApplication.desktop()
x = (desktop.width() - MainWindow.width()) // 2
y = (desktop.height() - MainWindow.height()) // 2
MainWindow.move(x,y)
MainWindow.show()
sys.exit(app.exec())#exec_()方法的作用是“进入程序的主循环直到exit()被调
You cannot and should not modify the GUI directly from another thread, in your case QTableWidget and QTableWidgetItem are part of the GUI so the code: self.tableWidget.setItem(2, 2, QTableWidgetItem(cnt)) is incorrect. What should be done is to send the information to the main thread through elements that are thread-safe such as signals, QEvents, etc.
On the other hand PyQt recommends not modifying the class it generates but creating a widget and using the generated class as an interface(1).
Considering the above the solution is:
import sys
import time
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Control_system(object):
def setupUi(self, Control_system):
Control_system.setObjectName("Control_system")
Control_system.resize(1004, 722)
Control_system.setFixedSize(1004, 722)
Control_system.setWindowIcon(QtGui.QIcon("images/icon.png"))
Control_system.setStyleSheet(
"QMainWindow{border-image:url(images/background.jpg)}"
)
self.centralwidget = QtWidgets.QWidget(Control_system)
self.centralwidget.setObjectName("centralwidget")
# 表格显示
self.tableWidget = QtWidgets.QTableWidget(self.centralwidget)
self.tableWidget.setGeometry(QtCore.QRect(130, 170, 752, 245))
self.tableWidget.setRowCount(8)
self.tableWidget.setColumnCount(6)
self.tableWidget.setObjectName("tableWidget")
self.tableWidget.horizontalHeader().setVisible(False)
self.tableWidget.horizontalHeader().setCascadingSectionResizes(False)
self.tableWidget.horizontalHeader().setDefaultSectionSize(125)
self.tableWidget.horizontalHeader().setHighlightSections(True)
self.tableWidget.horizontalHeader().setSortIndicatorShown(False)
self.tableWidget.verticalHeader().setVisible(False)
Control_system.setCentralWidget(self.centralwidget)
self.tableWidget.setAutoFillBackground(True)
self.tableWidget.setItem(0, 0, QtWidgets.QTableWidgetItem("机器编号"))
self.tableWidget.setItem(0, 1, QtWidgets.QTableWidgetItem("烟雾值"))
self.tableWidget.setItem(0, 2, QtWidgets.QTableWidgetItem("火焰值"))
self.tableWidget.setItem(0, 3, QtWidgets.QTableWidgetItem("温度值"))
self.tableWidget.setItem(0, 4, QtWidgets.QTableWidgetItem("电流值"))
self.tableWidget.setItem(0, 5, QtWidgets.QTableWidgetItem("电压值"))
font = QtGui.QFont()
font.setPointSize(15)
font.setBold(True)
self.tableWidget.item(0, 0).setFont(font)
self.tableWidget.item(0, 1).setFont(font)
self.tableWidget.item(0, 2).setFont(font)
self.tableWidget.item(0, 3).setFont(font)
self.tableWidget.item(0, 4).setFont(font)
self.tableWidget.item(0, 5).setFont(font)
self.label = QtWidgets.QLabel(self.centralwidget)
self.label.setGeometry(QtCore.QRect(360, 70, 300, 50))
self.label.setObjectName("label")
self.label.setAutoFillBackground(True)
self.label.setAlignment(QtCore.Qt.AlignCenter)
self.label.setStyleSheet("border-image:url(images/title.png)")
self.pushButton = QtWidgets.QPushButton(self.centralwidget)
self.pushButton.setGeometry(QtCore.QRect(730, 480, 121, 41))
self.pushButton.setObjectName("pushButton")
Control_system.setCentralWidget(self.centralwidget)
self.statusbar = QtWidgets.QStatusBar(Control_system)
self.statusbar.setObjectName("statusbar")
Control_system.setStatusBar(self.statusbar)
self.retranslateUi(Control_system)
QtCore.QMetaObject.connectSlotsByName(Control_system)
def retranslateUi(self, Control_system):
_translate = QtCore.QCoreApplication.translate
Control_system.setWindowTitle(_translate("Control_system", "实时监控系统"))
self.pushButton.setText(_translate("Control_system", "开始运行"))
class Control_system(QtWidgets.QMainWindow, Ui_Control_system):
def __init__(self, parent=None):
super().__init__(parent)
self.setupUi(self)
self.pushButton.clicked.connect(self.slotStart)
#QtCore.pyqtSlot()
def slotStart(self):
self.pushButton.setEnabled(False)
self.update_data_thread = UpdateData(self)
self.update_data_thread.dataChanged.connect(self.onDataChanged)
self.update_data_thread.start()
#QtCore.pyqtSlot(int, int, str)
def onDataChanged(self, row, column, text):
it = self.tableWidget.item(row, column)
if it is None:
it = QtWidgets.QTableWidgetItem()
self.tableWidget.setItem(row, column, it)
it.setText(text)
class UpdateData(QtCore.QThread):
dataChanged = QtCore.pyqtSignal(int, int, str)
def run(self):
cnt = 0
while True:
cnt += 1
self.dataChanged.emit(2, 2, str(cnt))
time.sleep(1)
if __name__ == "__main__":
app = QtWidgets.QApplication.instance()
if app is None:
app = QtWidgets.QApplication(sys.argv)
w = Control_system()
w.show()
sys.exit(app.exec_())
Update:
class Control_system(QtWidgets.QMainWindow, Ui_Control_system):
def __init__(self, parent=None):
super().__init__(parent)
self.setupUi(self)
self.pushButton.clicked.connect(self.slotStart)
self.pushButton_2.clicked.connect(self.slotStop)
#QtCore.pyqtSlot()
def slotStart(self):
# ...
#QtCore.pyqtSlot(int, int, str)
def onDataChanged(self, row, column, text):
it = self.tableWidget.item(row, column)
if it is None:
it = QtWidgets.QTableWidgetItem()
self.tableWidget.setItem(row, column, it)
it.setText(text)
#QtCore.pyqtSlot()
def slotStop(self):
self.update_data_thread.requestInterruption()
self.update_data_thread.quit()
self.update_data_thread.wait()
self.pushButton.setEnabled(True)
class UpdateData(QtCore.QThread):
dataChanged = QtCore.pyqtSignal(int, int, str)
def run(self):
cnt = 0
while not self.isInterruptionRequested(): # <---
cnt += 1
self.dataChanged.emit(2, 2, str(cnt))
time.sleep(1)
(1) Using the Generated Code

Is there a way to change a label of one window from another window?

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

Can't fill some cells of tablewidget. PyQt5

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

PyQt5: Fill combo-boxes with items from a table-widget

Here I have my Table Widget that the user will fill later:
class Ui_Form(object):
def setupUi(self, Form):
Form.setObjectName("Form")
Form.resize(238, 260)
self.tableWidget = QtWidgets.QTableWidget(Form)
self.tableWidget.setGeometry(QtCore.QRect(10, 10, 221, 241))
self.tableWidget.setObjectName("tableWidget")
self.tableWidget.setColumnCount(2)
self.tableWidget.setRowCount(7)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setVerticalHeaderItem(0, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setVerticalHeaderItem(1, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setVerticalHeaderItem(2, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setVerticalHeaderItem(3, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setVerticalHeaderItem(4, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setVerticalHeaderItem(5, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setVerticalHeaderItem(6, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setHorizontalHeaderItem(0, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setHorizontalHeaderItem(1, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setItem(0, 0, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setItem(0, 1, item)
self.retranslateUi(Form)
QtCore.QMetaObject.connectSlotsByName(Form)
And here is my Dialog window which contains a combobox:
class Ui_Dialog(object):
def setupUi(self, Dialog):
Dialog.setObjectName("Dialog")
Dialog.resize(281, 176)
self.comboBox = QtWidgets.QComboBox(Dialog)
self.comboBox.setGeometry(QtCore.QRect(90, 10, 71, 22))
self.comboBox.setObjectName("comboBox")
self.comboBox.addItem("")
self.comboBox_2 = QtWidgets.QComboBox(Dialog)
self.comboBox_2.setGeometry(QtCore.QRect(10, 10, 71, 22))
self.comboBox_2.setObjectName("comboBox_2")
self.comboBox_2.addItem("")
self.dateTimeEdit = QtWidgets.QDateTimeEdit(Dialog)
self.dateTimeEdit.setGeometry(QtCore.QRect(10, 60, 194, 22))
self.dateTimeEdit.setObjectName("dateTimeEdit")
self.label_2 = QtWidgets.QLabel(Dialog)
self.label_2.setGeometry(QtCore.QRect(10, 40, 91, 16))
self.label_2.setObjectName("label_2")
self.lineEdit = QtWidgets.QLineEdit(Dialog)
self.lineEdit.setGeometry(QtCore.QRect(150, 110, 113, 20))
self.lineEdit.setObjectName("lineEdit")
self.label_3 = QtWidgets.QLabel(Dialog)
self.label_3.setGeometry(QtCore.QRect(150, 90, 121, 16))
self.label_3.setObjectName("label_3")
self.lineEdit_2 = QtWidgets.QLineEdit(Dialog)
self.lineEdit_2.setGeometry(QtCore.QRect(10, 110, 113, 20))
self.lineEdit_2.setObjectName("lineEdit_2")
self.label_4 = QtWidgets.QLabel(Dialog)
self.label_4.setGeometry(QtCore.QRect(10, 90, 111, 16))
self.label_4.setObjectName("label_4")
self.pushButton = QtWidgets.QPushButton(Dialog)
self.pushButton.setGeometry(QtCore.QRect(150, 140, 111, 23))
self.pushButton.setObjectName("pushButton")
self.pushButton_2 = QtWidgets.QPushButton(Dialog)
self.pushButton_2.setGeometry(QtCore.QRect(10, 140, 111, 23))
self.pushButton_2.setObjectName("pushButton_2")
self.retranslateUi(Dialog)
QtCore.QMetaObject.connectSlotsByName(Dialog)
So, how do I fill the comboBox_2 exactly, with items from Table Widget?
I am thinking about some kind of cycle, but don't know how to realize it.
I already created classes for the Dialog window and Table Widget class.
class Dialog(QtWidgets.QDialog, Ui_Dialog):
def __init__(self, parent=None):
QtWidgets.QDialog.__init__(self, parent)
self.setupUi(self)
# cancel
self.pushButton_2.clicked.connect(self.reject)
# accept
self.pushButton.clicked.connect(self.accept)
self.dateTimeEdit.setDisplayFormat("d/M/yy hh:mm")
class Masters(QtWidgets.QDialog,Ui_Form):
def __init__(self, parent=None):
QtWidgets.QDialog.__init__(self, parent)
self.setupUi(self)
Full code(not including gui)
class Dialog(QtWidgets.QDialog, Ui_Dialog):
def __init__(self, parent=None):
QtWidgets.QDialog.__init__(self, parent)
self.setupUi(self)
# cancel
self.pushButton_2.clicked.connect(self.reject)
# accept
self.pushButton.clicked.connect(self.accept)
self.dateTimeEdit.setDisplayFormat("d/M/yy hh:mm")
def data(self):
master = self.comboBox_2.currentText()
service = self.comboBox.currentText()
name = self.lineEdit_2.text()
contact_number = self.lineEdit.text()
time = self.dateTimeEdit.time()
return master, service, name, contact_number, time
class Services(QtWidgets.QDialog,Ui_SForm):
def __init__(self, parent=None):
QtWidgets.QDialog.__init__(self, parent)
self.setupUi(self)
class Masters(QtWidgets.QDialog,Ui_Form):
def __init__(self, parent=None):
QtWidgets.QDialog.__init__(self, parent)
self.setupUi(self)
class Table2ListProxyModel(QtCore.QAbstractProxyModel):
def __init__(self, parent=None):
QtCore.QAbstractProxyModel.__init__(self, parent)
self.mapping = []
def setSourceModel(self, sourceModel):
sourceModel.dataChanged.connect(lambda: self.fixModel())
QtCore.QAbstractProxyModel.setSourceModel(self, sourceModel)
self.fixModel()
def mapFromSource(self, sourceIndex):
if sourceIndex.isValid():
key = self.mapping.index((sourceIndex.row(), sourceIndex.column()))
return self.index(key, 0)
return QtCore.QModelIndex()
def mapToSource(self, proxyIndex):
if proxyIndex.isValid():
r, c = self.mapping[proxyIndex.row()]
return self.sourceModel().index(r, c)
return QtCore.QModelIndex()
def rowCount(self, parent=QtCore.QModelIndex()):
return len(self.mapping)
def columnCount(self, parent=QtCore.QModelIndex()):
return 1
def index(self, row, column, parent=QtCore.QModelIndex()):
return self.createIndex(row, column)
def parent(self, child):
return QtCore.QModelIndex()
def fixModel(self):
self.layoutAboutToBeChanged.emit()
self.mapping = []
for c in range(self.sourceModel().columnCount()):
for r in range(self.sourceModel().rowCount()):
ix = self.sourceModel().index(r, c)
data = self.sourceModel().data(ix)
if data is not None and data != "":
self.mapping.append((r, c))
self.layoutChanged.emit()
class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
def __init__(self, parent=None):
QtWidgets.QMainWindow.__init__(self, parent)
self.setupUi(self)
self.addclient.clicked.connect(self.onAddClient)
self.uslugi.clicked.connect(self.AddService)
self.mastera.clicked.connect(self.AddMaster)
def AddService(self):
services = Services(self)
services.show()
def AddMaster(self):
masters = Masters(self)
masters.show()
def onAddClient(self):
dialog = Dialog(self)
if dialog.exec_() == QtWidgets.QDialog.Accepted:
master, service, name, contact_number, time = dialog.data()
row = int(QtCore.QTime(8, 0).secsTo(time)/(30*60))
if row >= 0:
for k, text in enumerate([master, service, name, contact_number]):
self.tableWidget.setItem(row, k+1, QtWidgets.QTableWidgetItem(text))
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
dialog = Dialog()
master = Masters()
proxy = Table2ListProxyModel()
proxy.setSourceModel(master.tableWidget.model())
dialog.comboBox_2.setModel(proxy)
w = MainWindow()
w.show()
sys.exit(app.exec_())
You can set the model on the combo-box to the model from the table-widget, and then assign a specific column for the combo-box to use. This will automatically update the combo-box to show whatever items are in the first column of the table-widget whenever it changes. A sort-filter can be used to remove any empty items.
To get this to work, your code will need to look something like this:
class Dialog(QtWidgets.QDialog, Ui_Dialog):
def __init__(self, parent=None):
QtWidgets.QDialog.__init__(self, parent)
...
# set the model
model = QtCore.QSortFilterProxyModel(self)
model.setSourceModel(parent.tableWidget.model())
model.setFilterRegExp('.*\S.*')
model.setFilterKeyColumn(1)
model.setDynamicSortFilter(True)
self.comboBox_2.setModel(model)
self.comboBox_2.setModelColumn(1)
model.sort(1, QtCore.Qt.AscendingOrder)
A robust way to pass data to a QComboBox is to use a model, for this QComboBox has the method setModel(), but an inconvenience for this case is that you can only get the data from a column of QTableWidget, a way to solve that inconvenience is use a proxy to convert the model as a table to a list:
class Table2ListProxyModel(QAbstractProxyModel):
def __init__(self, parent=None):
QAbstractProxyModel.__init__(self, parent)
self.mapping = []
def setSourceModel(self, sourceModel):
sourceModel.dataChanged.connect(lambda: self.fixModel())
QAbstractProxyModel.setSourceModel(self, sourceModel)
self.fixModel()
def mapFromSource(self, sourceIndex):
if sourceIndex.isValid():
key = self.mapping.index((sourceIndex.row(), sourceIndex.column()))
return self.index(key, 0)
return QModelIndex()
def mapToSource(self, proxyIndex):
if proxyIndex.isValid():
r, c = self.mapping[proxyIndex.row()]
return self.sourceModel().index(r, c)
return QModelIndex()
def rowCount(self, parent=QModelIndex()):
return len(self.mapping)
def columnCount(self, parent=QModelIndex()):
return 1
def index(self, row, column, parent=QModelIndex()):
return self.createIndex(row, column)
def parent(self, child):
return QModelIndex()
def fixModel(self):
self.layoutAboutToBeChanged.emit()
self.mapping = []
for c in range(self.sourceModel().columnCount()):
for r in range(self.sourceModel().rowCount()):
ix = self.sourceModel().index(r, c)
data = self.sourceModel().data(ix)
if data is not None and data != "":
self.mapping.append((r, c))
self.layoutChanged.emit()
class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
def __init__(self, parent=None):
QtWidgets.QMainWindow.__init__(self, parent)
self.setupUi(self)
self.addclient.clicked.connect(self.onAddClient)
self.uslugi.clicked.connect(self.AddService)
self.mastera.clicked.connect(self.AddMaster)
self.masters = Masters(self)
proxy = Table2ListProxyModel()
proxy.setSourceModel(self.masters.tableWidget.model())
self.dialog = Dialog(self)
self.dialog.comboBox_2.setModel(proxy)
def AddMaster(self):
self.masters.show()
def AddService(self):
services = Services(self)
services.show()
def onAddClient(self):
if self.dialog.exec_() == QtWidgets.QDialog.Accepted:
master, service, name, contact_number, time = self.dialog.data()
row = int(QtCore.QTime(8, 0).secsTo(time) / (30 * 60))
if row >= 0:
for k, text in enumerate([master, service, name, contact_number]):
self.tableWidget.setItem(row, k + 1, QtWidgets.QTableWidgetItem(text))
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
w = MainWindow()
w.show()
sys.exit(app.exec_())
Edit:
class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
def __init__(self, parent=None):
QtWidgets.QMainWindow.__init__(self, parent)
self.setupUi(self)
self.addclient.clicked.connect(self.onAddClient)
self.mastera.clicked.connect(self.AddMaster)
self.masters = Masters(self)
self.services = Services(self)
self.dialog = Dialog(self)
proxy = QtCore.QSortFilterProxyModel()
proxy.setSourceModel(self.masters.tableWidget.model())
proxy.setFilterRegExp(".*\S.*")
self.dialog.comboBox_2.setModel(proxy)
proxy2 = QtCore.QSortFilterProxyModel()
proxy2.setFilterRegExp(".*\S.*")
proxy2.setSourceModel(self.services.tableWidget.model())
self.dialog.comboBox.setModel(proxy2)
self.dialog.comboBox.setModelColumn(1)
def AddService(self):
self.services.show()
def AddMaster(self):
self.masters.show()
def onAddClient(self):
if self.dialog.exec_() == QtWidgets.QDialog.Accepted:
master, service, name, contact_number, time = self.dialog.data()
row = int(QtCore.QTime(8, 0).secsTo(time) / (30 * 60))
if row >= 0:
for k, text in enumerate([master, service, name, contact_number]):
self.tableWidget.setItem(row, k + 1, QtWidgets.QTableWidgetItem(text))
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
w = MainWindow()
w.show()
sys.exit(app.exec_())

Categories

Resources