pyqt表格中添加控件

     Qt的表格可以像excel一样,添加一些操作,例如下拉选择,添加按钮等,例如下面的例子

pyqt表格中添加控件

      QTableWidget类有setCellWidget方法,可以在表格中设置控件

    def setCellWidget(self, p_int, p_int_1, QWidget): # real signature unknown; restored from __doc__
        """ setCellWidget(self, int, int, QWidget) """
        pass

    Qt助手的解释如下:

void QTableWidget::setCellWidget(int row, int column, QWidget *widget)

Sets the given widget to be displayed in the cell in the given row and column, passing the ownership of the widget to the table.

If cell widget A is replaced with cell widget B, cell widget A will be deleted. For example, in the code snippet below, the QLineEdit object will be deleted.

  setCellWidget(row, column, new QLineEdit);
  ...
  setCellWidget(row, column, new QTextEdit);

This function was introduced in Qt 4.1.

See also cellWidget().

     示例代码:

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};')
        tableWidget.setCellWidget(0,1,combox)

        modifyButton = QPushButton('修改')
        modifyButton.setDown(True)
        modifyButton.setStyleSheet('QPushButton{margin:3px};')
        tableWidget.setCellWidget(0,2,modifyButton)
        tableWidget.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)

        self.setLayout(layout)

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

 

上一篇:反向链接是什么?


下一篇:构造器(无参构造方法)