PyQt5中向单元格添加控件

在PyQt5中,我们应如何向QTableWidget中的单元格添加控件呢?在本讲中给出了几个示例( 解释附在代码中)

setItem:将文本放到单元格中
setCellWidget:将控件放到单元格中
setStyleSheet:设置控件的样式(Qt StyleSheet)

import sys

from PyQt5.QtGui import *
from PyQt5.QtWidgets import *

class PlaceControlInCell(QWidget):
    def __init__(self):
        super(PlaceControlInCell, self).__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle("在单元格中放置控件")
        self.resize(430, 300)
        layout = QHBoxLayout()
        tableWidget = QTableWidget()

        # 指定行列数
        tableWidget.setRowCount(4)
        tableWidget.setColumnCount(3)

        layout.addWidget(tableWidget)

        tableWidget.setHorizontalHeaderLabels(['姓名', '性别', '年龄'])

        # 创建单元格文本
        textItem = QTableWidgetItem("老王")
        tableWidget.setItem(0, 0, textItem)

        # 创建下拉控件
        combox = QComboBox()
        combox.addItem("男")
        combox.addItem("女")

        # QSS Qt StyleSheet
        combox.setStyleSheet('QComboBox{margin:3px}')

        # 向QTableWidget添加控件
        tableWidget.setCellWidget(0, 1, combox)

        button = QPushButton("修改")

        # 设置默认为按下的状态
        button.setDown(True)
        button.setStyleSheet('QPushButton{margin:3px}')
        tableWidget.setCellWidget(0, 2, button)

        self.setLayout(layout)



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

你可能感兴趣的:(PyQt5)