[PyQt5] 表格控件(QTableWidget)

[PyQt5] 表格控件(QTableWidget)_第1张图片

import sys

from PyQt5.QtGui import QIcon
from PyQt5.QtWidgets import QMainWindow, QApplication, QTableWidget, QTableWidgetItem


class MainApp(QMainWindow):
    def __init__(self):
        super(MainApp, self).__init__()
        self.init_ui()

    def init_ui(self):
        self.setWindowTitle('我的窗口')
        self.setWindowIcon(QIcon('img/app.png'))

        # 创建一个4行3列的表格
        self.table_widget = QTableWidget(4, 3)

        # 设置表格数据标题
        self.table_widget.setHorizontalHeaderLabels(['名称', '性别', '位置'])

        # 添加数据
        item = QTableWidgetItem('孙悟空')
        self.table_widget.setItem(0, 0, item)
        item = QTableWidgetItem('男')
        self.table_widget.setItem(0, 1, item)
        item = QTableWidgetItem('刺客')
        self.table_widget.setItem(0, 2, item)

        item = QTableWidgetItem('虞姬')
        self.table_widget.setItem(1, 0, item)
        item = QTableWidgetItem('女')
        self.table_widget.setItem(1, 1, item)
        item = QTableWidgetItem('射手')
        self.table_widget.setItem(1, 2, item)

        item = QTableWidgetItem('张良')
        self.table_widget.setItem(2, 0, item)
        item = QTableWidgetItem('男')
        self.table_widget.setItem(2, 1, item)
        item = QTableWidgetItem('法师')
        self.table_widget.setItem(2, 2, item)

        item = QTableWidgetItem('蔡文姬')
        self.table_widget.setItem(3, 0, item)
        item = QTableWidgetItem('女')
        self.table_widget.setItem(3, 1, item)
        item = QTableWidgetItem('辅助')
        self.table_widget.setItem(3, 2, item)

        self.setCentralWidget(self.table_widget)

        self.resize(400, 200)
        self.show()


if __name__ == '__main__':
    app = QApplication(sys.argv)
    main_app = MainApp()
    sys.exit(app.exec_())

你可能感兴趣的:(PyQt5,pyqt5)