所以我有一个表,其中包含使用以下几行代码动态生成的多个复选框:
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)
我尝试将其调整为较小的值,但是它不起作用:
chkBoxItem.setSizeHint(QSize(10,10))
基本上,我想删除此文本标签,以便将复选框放置在单元格的中心
答案 0 :(得分:0)
void QTableWidget :: setCellWidget(int row,int column,QWidget * widget)
将给定的窗口小部件设置为在给定的行和列的单元格中显示,将窗口小部件的所有权传递给表。
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_())