凌的博客

您现在的位置是:首页  > 学无止境 > python

python

PyQt5 界面控件 QTableWidget

2019-08-24python0
#! /usr/bin/python
# -*- coding: utf-8 -*-
# datetime:2019/8/24 19:29
# software: PyCharm

import sys

from PyQt5.QtWidgets import QWidget, QApplication, QTableWidget, QHBoxLayout, QTableWidgetItem, QAbstractItemView, \
    QHeaderView, \
    QComboBox, QPushButton


class Table(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle("QTableWidget 例子")
        self.resize(500, 300)
        layout = QHBoxLayout()

        tableWidget = QTableWidget(4, 3)
        tableWidget.setHorizontalHeaderLabels(['姓名', '性别', '体重( kg )'])
        tableWidget.setVerticalHeaderLabels(["行1", "行2", "行3", "行4"])
        tableWidget.setSelectionBehavior(QAbstractItemView.SelectRows)

        # 将行与列的宽度高度与文本内容的宽高相匹配
        QTableWidget.resizeColumnsToContents(tableWidget)
        QTableWidget.resizeRowsToContents(tableWidget)

        # 设置表格头为伸缩模式
        tableWidget.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        # 将表格设置为禁止编辑
        tableWidget.setEditTriggers(QAbstractItemView.NoEditTriggers)

        # 表格头的显示与隐藏
        # tableWidget.verticalHeader().setVisible(False)
        # tableWidget.horizontalHeader().setVisible(False)

        # 添加数据
        newItem = QTableWidgetItem('张三')
        tableWidget.setItem(0, 0, newItem)

        newItem = QTableWidgetItem('男')
        tableWidget.setItem(0, 1, newItem)

        newItem = QTableWidgetItem('160')
        tableWidget.setItem(0, 2, newItem)

        # 在单元格内放置控件
        comBox = QComboBox()
        comBox.addItems(['男', '女'])
        comBox.addItem('未知')
        comBox.setStyleSheet('QComboBox{margin:3px}')
        tableWidget.setCellWidget(0, 1, comBox)

        searchBtn = QPushButton('修改')
        searchBtn.setDown(True)
        searchBtn.setStyleSheet('QPushButton{margin:3px}')
        tableWidget.setCellWidget(0, 2, searchBtn)

        layout.addWidget(tableWidget)
        self.setLayout(layout)


if __name__ == "__main__":
    app = QApplication(sys.argv)
    ex = Table()
    ex.show()
    sys.exit(app.exec_())


如果本文对您有所帮助,请支持下本站哦!!!^_^

文章评论

0条评论