【发布时间】:2023-03-09 09:15:02
【问题描述】:
我正在尝试创建一个表格小部件,其行数根据 SpinBox 变化。
我设法做到了。在表格小部件的每个单元格中,我有一个组合框。
我需要为表格小部件的每一行连接组合框。在接下来的两个组合框中自动选择“国家”时,会出现“首都”选项和对应的“城市”选项。
例如选择国家“美国”时:
- 首都:华盛顿
- 城市:芝加哥,纽约
我把代码写得更清楚。
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(0, 3)
layout.addWidget(self.table)
self.table.verticalHeader().setVisible(False)
for col, label in enumerate(('Country', 'Capital', 'City')):
header = QtWidgets.QTableWidgetItem(label)
self.table.setHorizontalHeaderItem(col, header)
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)
dic = {"Country": ['Argentina', 'USA', 'Spain'], "Capital": ['Buenos Aires', 'Washington D.C.','Madrid'], "City1": ["Rosario", "Chicago", "Barcelona"],
"City2": ["Bariloche", "New York", "Osasuna"]}
for i in range(self.table.columnCount()):
if i==0:
combobox1 = QtWidgets.QComboBox()
combobox1.addItems(dic["Country"])
self.table.setCellWidget(row, i, combobox1)
elif i==1:
combobox2 = QtWidgets.QComboBox()
combobox2.addItems(dic["Capital"])
self.table.setCellWidget(row, i, combobox2)
elif i==2:
combobox3 = QtWidgets.QComboBox()
combobox3.addItems(dic["City1"])
combobox3.addItems(dic["City2"])
self.table.setCellWidget(row, i, combobox3)
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
test = MainWindow()
test.show()
sys.exit(app.exec_())
【问题讨论】:
标签: python python-3.x pyqt pyqt5 pyqt4