我正在尝试创建一个包含160行的表,然后在每个奇数行中插入QCheckBox
,特别是在第10列。问题是,我必须创建80 QCheckBox
(每行一个,因此可以由用户单独分配)...
逐个创建我拥有的9个项目的80个QCheckBox
个对象要做的只是废话!
有没有办法通过循环来做到这一点?我想不出任何东西,我搜索了答案,一无所获。
[...]
# importing PySide
from PySide import QtGui, QtCore
[...]
# Creating a Table
class Table(QtGui.QDialog):
def __init__(self, parent=None):
super(Table, self).__init__(parent)
self.table = QtGui.QTableWidget()
self.table.setRowCount(160)
self.table.setColumnCount(10)
# This is the tricky part:
chkBoxItem = QtGui.QTableWidgetItem()
chkBoxItem.setFlags(QtCore.Qt.ItemIsUserCheckable|QtCore.Qt.ItemIsEnabled)
chkBoxItem.setCheckState(QtCore.Qt.Unchecked)
chkBoxItem2 = QtGui.QTableWidgetItem()
chkBoxItem2.setFlags(QtCore.Qt.ItemIsUserCheckable|QtCore.Qt.ItemIsEnabled)
chkBoxItem2.setCheckState(QtCore.Qt.Unchecked)
chkBoxItem3 = QtGui.QTableWidgetItem()
chkBoxItem3.setFlags(QtCore.Qt.ItemIsUserCheckable|QtCore.Qt.ItemIsEnabled)
chkBoxItem3.setCheckState(QtCore.Qt.Unchecked)
[...]
# Then insert all of them in the Table:
self.table.setItem(0, 10, chkBoxItem)
self.table.setItem(2, 10, chkBoxItem2)
self.table.setItem(4, 10, chkBoxItem3)
self.table.setItem(6, 10, chkBoxItem4)
self.table.setItem(8, 10, chkBoxItem5)
self.table.setItem(10, 10, chkBoxItem6)
self.table.setItem(12, 10, chkBoxItem7)
[...]
答案 0 :(得分:1)
此基本脚本创建一个包含160 * 10 QTable和QPushButton的UI。 每个奇数行,在第10列的单元格中添加一个复选框。 单击该按钮会显示所有复选框的状态列表。
<强>国强>:
注意:
这是使用PyQt
进行的代码:
import math, sys
from PyQt4.QtCore import Qt, QTimer
from PyQt4.QtGui import *
class MainWindow(QMainWindow):
def __init__(self, parent = None):
QMainWindow.__init__(self, parent)
#Create Basic UI
self.mainWidget = QWidget(self)
self.table = QTableWidget()
self.table.setRowCount(160)
self.table.setColumnCount(10)
self.button = QPushButton("Print stuff")
layout = QVBoxLayout(self.mainWidget)
layout.addWidget(self.table)
layout.addWidget(self.button)
self.setCentralWidget(self.mainWidget)
self.button.clicked.connect(self.printStuff)
#################
#Fill the table
self.rowRange = range(0, self.table.rowCount(), 2)
for i in self.rowRange:
chkBoxItem = QTableWidgetItem()
chkBoxItem.setFlags(Qt.ItemIsUserCheckable|Qt.ItemIsEnabled)
chkBoxItem.setCheckState(Qt.Unchecked)
self.table.setItem(i, 9, chkBoxItem)
###############
def printStuff(self): #You can remove this, this is for testing purpose only
print [(i+1, self.table.item(i, 9).checkState()) for i in self.rowRange]
if __name__ == "__main__":
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())