How to check if a checkbox is checked in a qtablewidget? - python

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)

Related

How to edit string as items from QListWidget using with QDataWidgetMapper

I am using QListWidget, QSqlTableModel, QtableView and QDataWidgetMapper. QListWidget is ItemIsUserCheckable.
I am able to save selected items from QListWidget into QtSql table in a single field as string format(converting list items into string as "Green, Green Grapes, Oranges".
But at the same time i want to change the selected item and update the items from QListWidget of the String data. How to do. Is it possible. Or PLease let me know if any other solution.
Below is the Example code:
from PyQt5 import QtCore, QtGui, QtWidgets, QtSql
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtSql import *
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(391, 496)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.listWidget = QtWidgets.QListWidget(self.centralwidget)
self.listWidget.setGeometry(QtCore.QRect(9, 9, 373, 188))
self.listWidget.setObjectName("listWidget")
self.save_btn = QtWidgets.QPushButton(self.centralwidget)
self.save_btn.setGeometry(QtCore.QRect(100, 230, 75, 23))
self.save_btn.setObjectName("save_btn")
self.label = QtWidgets.QLabel(self.centralwidget)
self.label.setGeometry(QtCore.QRect(9, 203, 27, 16))
self.label.setObjectName("label")
self.lineEdit = QtWidgets.QLineEdit(self.centralwidget)
self.lineEdit.setGeometry(QtCore.QRect(56, 203, 181, 20))
self.lineEdit.setObjectName("lineEdit")
self.update_btn = QtWidgets.QPushButton(self.centralwidget)
self.update_btn.setGeometry(QtCore.QRect(293, 229, 75, 23))
self.update_btn.setObjectName("update_btn")
self.edit_btn = QtWidgets.QPushButton(self.centralwidget)
self.edit_btn.setGeometry(QtCore.QRect(199, 229, 75, 23))
self.edit_btn.setObjectName("edit_btn")
self.tableView = QtWidgets.QTableView(self.centralwidget)
self.tableView.setGeometry(QtCore.QRect(9, 258, 373, 188))
self.tableView.setObjectName("tableView")
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 391, 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)
db = QtSql.QSqlDatabase.addDatabase("QSQLITE")
db.setDatabaseName("fruites.db")
if db.open():
if db.open():
query = QSqlQuery()
query.exec_("""CREATE TABLE IF NOT EXISTS store(name TEXT, items TEXT)""")
self.store_model = QtSql.QSqlTableModel()
self.store_model.setTable("store")
self.store_model.select()
self.tableView.setModel(self.store_model)
list_ = ["Green", "Green Apple","Green Grapes", "Bananas", "Oranges"]
list_ = dict.fromkeys(list_, 0)
for i in list_:
item = QtWidgets.QListWidgetItem(i)
item.setFlags(item.flags() | QtCore.Qt.ItemIsUserCheckable)
item.setCheckState(QtCore.Qt.Unchecked)
self.listWidget.addItem(item)
self.save_btn.clicked.connect(self.save_item)
self.edit_btn.clicked.connect(self.edit_item)
self.update_btn.clicked.connect(self.submit_item)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.save_btn.setText(_translate("MainWindow", "Save"))
self.label.setText(_translate("MainWindow", "Name"))
self.update_btn.setText(_translate("MainWindow", "Update"))
self.edit_btn.setText(_translate("MainWindow", "Edit"))
def save_item(self):
name = self.lineEdit.text()
strng = ''
checked = []
for row in range(self.listWidget.count()):
item = self.listWidget.item(row)
if item.checkState():
checked.append(item)
strng = ", " .join(i.text() for i in checked)
r = self.store_model.record()
r.setValue("name", name)
r.setValue("items", strng)
self.store_model.insertRecord(-1, r)
self.store_model.select()
self.lineEdit.clear()
for i in range(self.listWidget.count()):
item = self.listWidget.item(i)
item.setCheckState(QtCore.Qt.Unchecked)
def edit_item(self):
selected = self.tableView.selectedIndexes()
if not self.store_model.rowCount():
return
index = self.tableView.currentIndex()
if index.isValid():
row = index.row()
else:
row = 0
self.store_mapper = QtWidgets.QDataWidgetMapper()
self.store_mapper.setSubmitPolicy(QtWidgets.QDataWidgetMapper.ManualSubmit)
self.store_mapper.setModel(self.tableView.model())
self.store_mapper.addMapping(self.lineEdit, 0)
self.store_mapper.addMapping(self.listWidget, 1)
self.store_mapper.setCurrentIndex(row)
def submit_item(self):
self.store_mapper.submit()
self.lineEdit.clear()
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_())

PyQt5 - Create a check item in a column of a table widget even with the number of rows varying from a spinbox

I'm new to PyQt5 and I'm using Qtdesigner to develop an interface.
I am controlling the number of rows of a Table Widget from the spinbox. However, when changing the number of rows I need to keep the check option for column a.
I managed to change the number of rows according to valueChanged in the spinbox, but the loop I created to create the check regardless of the number of rows did not work.
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(519, 468)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.spinBox = QtWidgets.QSpinBox(self.centralwidget)
self.spinBox.setGeometry(QtCore.QRect(80, 131, 41, 31))
self.spinBox.setProperty("value", 2)
self.spinBox.setObjectName("spinBox")
self.tableWidget = QtWidgets.QTableWidget(self.centralwidget)
self.tableWidget.setGeometry(QtCore.QRect(160, 80, 341, 101))
self.tableWidget.setObjectName("tableWidget")
self.tableWidget.setColumnCount(2)
self.tableWidget.setRowCount(2)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setVerticalHeaderItem(0, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setVerticalHeaderItem(1, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setHorizontalHeaderItem(0, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setHorizontalHeaderItem(1, item)
item = QtWidgets.QTableWidgetItem()
item.setFlags(QtCore.Qt.ItemIsUserCheckable|QtCore.Qt.ItemIsEnabled)
item.setCheckState(QtCore.Qt.Checked)
self.tableWidget.setItem(0, 0, item)
item = QtWidgets.QTableWidgetItem()
item.setFlags(QtCore.Qt.ItemIsEnabled)
item.setCheckState(QtCore.Qt.Checked)
self.tableWidget.setItem(1, 0, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setItem(1, 1, item)
self.tableWidget.verticalHeader().setVisible(False)
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 519, 21))
self.menubar.setObjectName("menubar")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
self.spinBox.valueChanged['int'].connect(self.tableWidget.setRowCount)
for i in range(self.tableWidget.rowCount()):
item = QtWidgets.QTableWidgetItem()
item.setFlags(QtCore.Qt.ItemIsEnabled)
item.setCheckState(QtCore.Qt.Checked)
self.tableWidget.setItem(i, 0, item)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
item = self.tableWidget.verticalHeaderItem(0)
item.setText(_translate("MainWindow", "d"))
item = self.tableWidget.verticalHeaderItem(1)
item.setText(_translate("MainWindow", "e"))
item = self.tableWidget.horizontalHeaderItem(0)
item.setText(_translate("MainWindow", "a"))
item = self.tableWidget.horizontalHeaderItem(1)
item.setText(_translate("MainWindow", "c"))
__sortingEnabled = self.tableWidget.isSortingEnabled()
self.tableWidget.setSortingEnabled(False)
self.tableWidget.setSortingEnabled(__sortingEnabled)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
item = self.tableWidget.verticalHeaderItem(0)
item.setText(_translate("MainWindow", "d"))
item = self.tableWidget.verticalHeaderItem(1)
item.setText(_translate("MainWindow", "e"))
item = self.tableWidget.horizontalHeaderItem(0)
item.setText(_translate("MainWindow", "a"))
item = self.tableWidget.horizontalHeaderItem(1)
item.setText(_translate("MainWindow", "c"))
__sortingEnabled = self.tableWidget.isSortingEnabled()
self.tableWidget.setSortingEnabled(False)
self.tableWidget.setSortingEnabled(__sortingEnabled)
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_())
First of all, it seems like you're editing the output of a pyuic generated file, or you're trying to mimic its behavior. In any case, this is something that should never be done.
Those files are meant to be left as they are, and you should only use them as modules; to know how to correctly do this, read more about using Designer. If you're trying to mimic their behavior, well, you shouldn't: the way pyuic files are treated is only considered as an "interpretation layer" in order to create the GUI objects and make them accessible from python. If you're building the GUI from code, just subclass the QWidget you want to use (QWidget, QDialog or QMainWindow, usually).
Now, the problem is that whenever setRowCount() is called...:
[it] Sets the number of rows in this table's model to rows. If this is less than rowCount(), the data in the unwanted rows is discarded.
This obviously means that, if you're removing rows, you're losing all items in that row (including the fact that they are checkable at all).
To correctly update the contents and add checkable items, you'll need to do that in a specific method that dynamically removes or adds items.
In the next example I'll show how to correctly implement this (and in an easier, clearer way):
from PyQt5 import QtCore, QtWidgets
class MainWindow(QtWidgets.QMainWindow):
def __init__(self):
super().__init__()
central = QtWidgets.QWidget()
self.setCentralWidget(central)
layout = QtWidgets.QHBoxLayout(central)
self.spin = QtWidgets.QSpinBox()
layout.addWidget(self.spin)
self.table = QtWidgets.QTableWidget(2, 2)
layout.addWidget(self.table)
self.table.verticalHeader().setVisible(False)
for col, label in enumerate(('a', 'c')):
header = QtWidgets.QTableWidgetItem(label)
self.table.setHorizontalHeaderItem(col, header)
if col:
continue
for row in range(self.table.rowCount()):
item = QtWidgets.QTableWidgetItem()
item.setFlags(item.flags() | QtCore.Qt.ItemIsUserCheckable)
item.setCheckState(QtCore.Qt.Checked)
self.table.setItem(row, col, item)
self.spin.setValue(self.table.rowCount())
self.spin.valueChanged.connect(self.setRowCount)
def setRowCount(self, count):
if count == self.table.rowCount():
return
# if there are too many rows, remove them
while self.table.rowCount() > count:
self.table.removeRow(self.table.rowCount() - 1)
# if rows are going to be added, create checkable items for them
while self.table.rowCount() < count:
row = self.table.rowCount()
self.table.insertRow(row)
item = QtWidgets.QTableWidgetItem()
item.setFlags(item.flags() | QtCore.Qt.ItemIsUserCheckable)
item.setCheckState(QtCore.Qt.Checked)
self.table.setItem(row, 0, item)
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
test = MainWindow()
test.show()
sys.exit(app.exec_())
As a side note, a couple of considerations:
a layout manager should always be used for widgets, otherwise the contents might become invisible or won't adjust their position;
you're defining retranslateUi twice; I suppose that's something that remained from editing the pyuic file, but, in any case, redifining a function with the same name results in overwriting it (unless each of them have an unique decorator)

How to save Qlistwidget items in database or in txt file

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

Switch button in pyqt

Is it possible to create a switch button with pyqt5?
I'm designing a filtering tool in python using pyqt5. The user is supposed to be able to apply a filter or its complement on some data and even combine filters.
I display possible filters in qtablewidget where the user can choose filters to apply using checkboxes. In each row, checkboxes are exclusives i.e. the user can not select a filter and its complement at the same time.
But the problem is that once we select a checkbox in a row, we cannot deselect it unless we select its opposite.
In fact, when the filters are just loaded , all the boxes are unchecked (they are empty in a way) so I can choose which filter to apply but when I want to choose an other filter, one of the boxes of the precedent filter still checked (either box Filter or box Complement is checked) and I can not switch it off.
That's why I thought about adding a switch button in each row to disable a filter. By doing this I will be able to take in consideration or not the checked attribute.
Here is an example of what I want :
Below an reproductible 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")
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", "complement"))
self.pushButton_Save.setText(_translate("MainWindow", "Save"))
self.pushButton_Save.clicked.connect(self.bindSave)
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)
if __name__ == "__main__":
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()
Like others have suggested, you could enable/disable filters by adding a third column to the table and setting each item widget in this column to a like you did for ch_box1 and ch_box2. You can use slots and signals to manipulate the check buttons (for example enable/disable them depending on the state of the switch).
To create custom switches like in the picture in the OP, you could sub-class QPushButton and overriding paintEvent, e.g. (note that I've omitted the code that was the same as the code in the reproducable example in the original post)
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import Qt, QRect
import sys
class MySwitch(QtWidgets.QPushButton):
def __init__(self, parent = None):
super().__init__(parent)
print('init')
self.setCheckable(True)
self.setMinimumWidth(66)
self.setMinimumHeight(22)
def paintEvent(self, event):
label = "ON" if self.isChecked() else "OFF"
bg_color = Qt.green if self.isChecked() else Qt.red
radius = 10
width = 32
center = self.rect().center()
painter = QtGui.QPainter(self)
painter.setRenderHint(QtGui.QPainter.Antialiasing)
painter.translate(center)
painter.setBrush(QtGui.QColor(0,0,0))
pen = QtGui.QPen(Qt.black)
pen.setWidth(2)
painter.setPen(pen)
painter.drawRoundedRect(QRect(-width, -radius, 2*width, 2*radius), radius, radius)
painter.setBrush(QtGui.QBrush(bg_color))
sw_rect = QRect(-radius, -radius, width + radius, 2*radius)
if not self.isChecked():
sw_rect.moveLeft(-width)
painter.drawRoundedRect(sw_rect, radius, radius)
painter.drawText(sw_rect, Qt.AlignCenter, label)
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
....
self.tableWidget.setColumnCount(4)
....
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setHorizontalHeaderItem(3, item)
...
def retranslateUi(self, MainWindow):
...
item = self.tableWidget.horizontalHeaderItem(3)
item.setText(_translate("MainWindow", "status"))
def bindSave(self):
...
ch_bx3 = MySwitch()
ch_bx3.setChecked(True)
ch_bx3.clicked.connect(ch_bx1.setEnabled)
ch_bx3.clicked.connect(ch_bx2.setEnabled)
self.tableWidget.setCellWidget(numRows, 3, ch_bx3)
if __name__ == "__main__":
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()
app.exec()
Screenshot:

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

Categories

Resources