Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove label from dynamically generated check box in PyQt5?

So I have a table which has several checkboxes dynamically generated using these lines of codes:

chkBoxItem = QTableWidgetItem()
chkBoxItem.setTextAlignment(Qt.AlignHCenter)
chkBoxItem.setFlags(QtCore.Qt.ItemIsUserCheckable | QtCore.Qt.ItemIsEnabled)
chkBoxItem.setCheckState(QtCore.Qt.Unchecked) 
ui.columnTable.cellChanged.connect(self.checkColumnDataCheckbox)
ui.columnTable.setItem(i , 0, chkBoxItem)

I have tried resizing it to a small value but it's not working:

chkBoxItem.setSizeHint(QSize(10,10))

Seems like it doesn't go beyond a certain minimum width and height.
Here's how it looked: enter image description here

Basically, I want to remove this text label so the checkbox can be positioned at the center of the cell

like image 213
akmalzamri Avatar asked Dec 16 '25 21:12

akmalzamri


1 Answers

void QTableWidget::setCellWidget(int row, int column, QWidget *widget)

Sets the given widget to be displayed in the cell in the given row and column, passing the ownership of the widget to the table.

import sys
from PyQt5.QtGui     import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore    import *

class Window(QWidget):
    def __init__(self, rows, columns):
        super().__init__()
        
        self.table = QTableWidget(rows, columns, self)
        
        for row in range(rows):
            widget   = QWidget()
            checkbox = QCheckBox()
            checkbox.setCheckState(Qt.Unchecked)
            layoutH = QHBoxLayout(widget)
            layoutH.addWidget(checkbox)
            layoutH.setAlignment(Qt.AlignCenter)
            layoutH.setContentsMargins(0, 0, 0, 0)
            
            self.table.setCellWidget(row, 0, widget)                  # <----
            self.table.setItem(row, 1, QTableWidgetItem(str(row)))
            
        self.button = QPushButton("Control selected QCheckBox")
        self.button.clicked.connect(self.ButtonClicked)
        
        layoutV     = QVBoxLayout(self)
        layoutV.addWidget(self.table)
        layoutV.addWidget(self.button)


    def ButtonClicked(self):
        checked_list = []
        for i in range(self.table.rowCount()):
            if self.table.cellWidget(i, 0).findChild(type(QCheckBox())).isChecked():
                checked_list.append(self.table.item(i, 1).text())
        print(checked_list)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = Window(3, 3)
    window.resize(350, 300)
    window.show()
    sys.exit(app.exec_())

enter image description here

like image 178
S. Nick Avatar answered Dec 19 '25 11:12

S. Nick



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!