写一个在tableWidget显示一组数据的代码
时间: 2024-05-02 16:16:53 浏览: 13
以下是使用 PyQt5 的代码示例,可以在 tableWidget 中显示一组数据:
```python
from PyQt5.QtWidgets import QApplication, QMainWindow, QTableWidget, QTableWidgetItem
import sys
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setGeometry(100, 100, 500, 500)
self.setWindowTitle("Table Widget Example")
data = [[1, "John", 25, "Male"],
[2, "Alice", 20, "Female"],
[3, "Bob", 30, "Male"],
[4, "Mary", 27, "Female"],
[5, "David", 22, "Male"]]
# Create table widget
table_widget = QTableWidget()
table_widget.setRowCount(len(data))
table_widget.setColumnCount(len(data[0]))
self.setCentralWidget(table_widget)
# Set table headers
headers = ["ID", "Name", "Age", "Gender"]
table_widget.setHorizontalHeaderLabels(headers)
# Insert data into table
for row in range(len(data)):
for column in range(len(data[0])):
item = QTableWidgetItem(str(data[row][column]))
table_widget.setItem(row, column, item)
if __name__ == '__main__':
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
```
这段代码创建了一个窗口,并在其中创建了一个 tableWidget,然后将一组数据插入到 tableWidget 中,并设置了表头。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)