Is there a way to check which check boxes have been checked in a PyQt5 table

pyqt multiple checkboxes
pyqt checkbox set checked
pyqt5 checkbox
pyqt checkbox checked
qcheckbox example
qcheckbox set checked
check if a checkbox is checked pyqt5

I'm attempting to make a room booking system, using a table. In the table I have check boxes, I would like it so that when the user clicks the book button, the program would see which check boxes have been checked, so that it can remove those check boxes from the table.

I have created the table through PyQt5 designer, with checkboxes in each space of the table like this:

The UI file code has many lines like this:

        item = QtWidgets.QTableWidgetItem()
        self.tableWidget.setItem(0, 0, item)
        item = QtWidgets.QTableWidgetItem()
        self.tableWidget.setItem(0, 1, item)

Does this mean that the check boxes are all called item? is there a way in which I can a separate name for each check boxes?

Sorry if this seems like a basic question - Thanks in advance

You have to iterate over the table and do a check of the status of each item, using the filtered items you can get the row and column with what you can get the labels.

from PyQt5 import QtCore, QtGui, QtWidgets

class Widget(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super(Widget, self).__init__(parent)
        self.tableWidget = QtWidgets.QTableWidget(6, 5)
        self.book_button = QtWidgets.QPushButton("Book")

        lay = QtWidgets.QVBoxLayout(self)

        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)
                self.tableWidget.setItem(i, j, item)

    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:

        for it in items:
            r = it.row()
            c = it.column()
            v, h = self.tableWidget.horizontalHeaderItem(c).text(), self.tableWidget.verticalHeaderItem(r).text()
            print(h, v)

if __name__ == '__main__':
    import sys
    app = QtWidgets.QApplication(sys.argv)
    w = Widget()

PyQt - QCheckBox Widget, PyQt - QCheckBox Widget - A rectangular box before the text label appears when a In order to restrict the choice to one of the available items, the check boxes must be The following table lists commonly used QCheckBox class methods − The isChecked() function is used to check if the button is checked or not. How do I check if a checkbox is checked or unchecked? (In QTreeWidget) But there's no way to prevent someone else to re-declare such a variable -- thus ignoring

Just modify a bit the code above!

1) in the constructor declare the empty list value.

self._checked_items = []

2) inside the 'book_clicked' method add line:

self._checked_items.append([h, v])

3) declare a getter of checked_items:

def checked_items(self):
    return self._checked_items

4) print checked_items in the main method:


But I suggest you to use QTableView() , not QTableWidget(). QTableWidget() is item based, QTableView() is model based.

Of cause, at the first time it looks like more complicated, but later , when you understand how to use model based widgets you will love it!

What you have to do is to implement custom CheckedItemsModel , which extends QAbstractItemModel. Look at the documentation, you'll find a lot of examples.

PyQt5 - checkState() method for Check Box, There are basically two states in check box that are checked or unchecked, although using setTristate method we can add an intermediate state. checkState method is used to check the state of the check box, it returns CheckState object but when we print it output will be as follows: 0 for un-checked state. You can insert a checkbox in a standard way by using the following code: QTableWidgetItem *pItem = new QTableWidgetItem(); pItem->setCheckState(Qt::Checked); pMyTableWidget->setItem(0,0,pItem); As you can see in the image below the checkbox is showed but it is on the left side since the original idea is to have a checkbox and some text.

I did it for you , you are lucky)))

The main Window.

from PyQt5 import QtWidgets
from PyQt5.QtWidgets import QHeaderView

from examples.checkedItemsModel import CheckedItemsModel
from examples.checkedItemsUI import Ui_CheckedItemsView

class CheckedItems(QtWidgets.QMainWindow):
    def __init__(self, model= None, parent = None):
        super(CheckedItems, self).__init__(parent)

        self._ui = Ui_CheckedItemsView()

        self._model = model


        # set the table model

        # create connecitons

    def print_checked_items(self):
        model = self._ui.ui_table_view.model()

        items = model.checkedItems()

if __name__ == '__main__':
    import sys
    app = QtWidgets.QApplication(sys.argv)

    # data for table creation
    column_headers = ['P1', 'P2', 'P3', 'P4', 'P5', 'P6']
    row_headers = ['C101', 'C214', 'C320', 'F04', 'E201']

    # create table model
    model = CheckedItemsModel(column_headers, row_headers)

    # pass model to custom widget
    w = CheckedItems(model)


Realization of the model:

import typing
from PyQt5 import QtCore
from PyQt5.QtCore import QAbstractTableModel, Qt, QModelIndex

class CheckedItemsModel(QAbstractTableModel):
    def __init__(self, column_headers= [], row_headers=[], parent = None):
        super(CheckedItemsModel, self).__init__(parent)

        self._column_headers = column_headers
        self._row_headers = row_headers

        # create all unchecked items by default
        self._items = []
        for i in range(len(self._row_headers)):
            for j in range(len(self._column_headers)):

    def rowCount(self, parent: QModelIndex = QtCore.QModelIndex()) -> int:
        return len(self._row_headers)

    def columnCount(self, parent: QModelIndex = ...) -> int:
        return len(self._column_headers)

    def data(self, index: QModelIndex, role: int = QtCore.Qt.DisplayRole) -> typing.Any:
        if role == QtCore.Qt.DisplayRole:
            return ''#str(index.row()) + ', ' + str(index.column())

        if role == QtCore.Qt.CheckStateRole:
            if self._items[index.row()][index.column()] == Qt.Checked:
                return QtCore.Qt.Checked
                return QtCore.Qt.Unchecked

    def headerData(self, section: int, orientation: Qt.Orientation, role: int = ...) -> typing.Any:
        if role == QtCore.Qt.DisplayRole:
            if orientation == Qt.Horizontal:
                return self._column_headers[section]
                return self._row_headers[section]

    def setData(self, index: QModelIndex, value: typing.Any, role: int = QtCore.Qt.EditRole) -> bool:
        if role == Qt.EditRole:
            self._items[index.row()][index.column()] = value
            self.dataChanged.emit(index, index)

            return True

        if role == Qt.CheckStateRole:
            self._items[index.row()][index.column()] = value
            self.dataChanged.emit(index, index)

            return True

    def flags(self, index: QModelIndex):
        return Qt.ItemIsUserCheckable | Qt.ItemIsEnabled

    def checkedItems(self):
        items = []

        for i in range(self.rowCount()):
            for j in range(self.columnCount()):
                if self._items[i][j] == QtCore.Qt.Checked:
                    items.append('(' + str(self._row_headers[i]) + ', ' + str(self._column_headers[j]) + ')')

        return items

And the View class(automatically converted .ui file to .py) from Qt Designer:

# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'ui_CheckedItems.ui'
# Created by: PyQt5 UI code generator 5.9.2
# WARNING! All changes made in this file will be lost!

from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_CheckedItemsView(object):
    def setupUi(self, CheckedItemsView):
        CheckedItemsView.resize(685, 470)
        self.centralwidget = QtWidgets.QWidget(CheckedItemsView)
        self.horizontalLayout = QtWidgets.QHBoxLayout(self.centralwidget)
        self.verticalLayout = QtWidgets.QVBoxLayout()
        self.ui_table_view = QtWidgets.QTableView(self.centralwidget)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.MinimumExpanding, QtWidgets.QSizePolicy.MinimumExpanding)
        self.ui_table_view.setMinimumSize(QtCore.QSize(200, 200))
        self.ui_result = QtWidgets.QTextEdit(self.centralwidget)
        self.buttonsLayout = QtWidgets.QHBoxLayout()
        spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
        self.btn_book = QtWidgets.QPushButton(self.centralwidget)
        spacerItem1 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
        self.verticalLayout.setStretch(0, 5)
        self.verticalLayout.setStretch(1, 1)


    def retranslateUi(self, CheckedItemsView):
        _translate = QtCore.QCoreApplication.translate
        CheckedItemsView.setWindowTitle(_translate("CheckedItemsView", "MainWindow"))
        self.btn_book.setText(_translate("CheckedItemsView", "Book"))

How the program look like, when you execute

QTableWidgetItem — Qt for Python, QTableWidgetItem�. The QTableWidgetItem class provides an item for use with the QTableWidget class. table widgets. Items usually contain text, icons, or checkboxes. The Checkable items can be checked and unchecked with the setCheckState() function. Sets the check state of the table item to be state . See also. Is there a way to add a "Select All Checkbox" to a QTableWidget in the first header column? I mean, I found that I can add checkboxes on rows beneath the header, just not a checkbox in the header itself. I tried the following, but it shows no change: //

QStandardItem — Qt for Python, The QStandardItem class provides an item for use with the QStandardItemModel Items usually contain text, icons, or checkboxes. Items can be positioned in the child table with setChild() . Returns the checked state of the item. Returns the child item at ( row , column ) if one has been set; otherwise returns None . Adding Awesomeness – Check boxes! As we have a developer tab with us, now we can add check boxes. Check boxes are basically one of the form controls available in Excel. To add check boxes go through following steps: Step 1: Go to developer tab > Controls group > click Insert drop down > under form controls sub-group click check box icon.

Transmit extra data with signals in PyQt5 & PySide2 — Learn PyQt5 , a QAction has a .triggered that fires when that particular action has been activated. The triggered signal emits a single piece of data -- the checked state of the This is a powerful way to extend or modify the built-in signals provided by Qt. setCentralWidget(checkbox) # SLOT: Accepts the check value. def result( self,� Perhaps insert a symbol or the character code for a checkbox? You can go to Insert > Symbol, change the font to Windings and browse the symbols for different examples of check boxes and boxes already checked. You can also just hold the Alt key down and key in the character code. Try Alt + 0168 for an empty box and Alt + 0254 for a checked box.

PyQt5 Creating QCheckBox With Signals (Python GUI Development , Check our blog for source code This want to show you Duration: 17:34 Posted: 10 Dec 2018 Check boxes currently aren't available in Google Docs documents. You can add a check box image, but it won't be clickable (if that's what you're trying to do). If you need to create a form with check boxes, would Google Forms be a better option?

  • what is the name of check box?
  • I'm not sure, as I said I designed it in PyQt designer, so I used the QTableWidget, double clicked on it, went to items, properties then under flags I checked user Checkable.
  • No, I think you did not understand me, you want to identify the checkbox so I wonder what data you want to get from the item, in my answer I have proposed to print the label of the row and the column
  • How can I have it so that instead of printing (h, v), they instead are added to a single array or list, to then be printed as one.
  • Also how would I remove the check box after this