qtablewidget设置水平标题标签可编辑添加行

时间:2018-11-21 12:25:34

标签: python python-3.x pyqt pyqt5 qtablewidget

如何通过双击在qtablewidget中为添加的行编辑水平标题的标签?我从here获得了代码并对其进行了调整,但它不会更改添加列的名称。 我正在使用python 3.6和pyqt5。

const connection = await getConnection();
userIds.forEach(async (userId, i) => {
  connection
    .createQueryBuilder()
    .relation(Pin, "user")
    .of(pinIds[i])
    .set(userId);

  connection
    .createQueryBuilder()
    .relation(Pin, "location")
    .of(pinIds[i])
    .set(locationIds[i]);
});

1 个答案:

答案 0 :(得分:2)

当添加行或列并不意味着已经创建了相应的QTableWidgetItems时,在这种情况下仅修改了列数,因此新列的标题中没有QTableWidgetItem,因此解决方案是如有必要,请创建它。

from PyQt5 import QtCore, QtWidgets

class MyWindow(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super(MyWindow, self).__init__(parent)

        self.table = QtWidgets.QTableWidget(5,5)
        self.table.setHorizontalHeaderLabels(['1', '2', '3', '4', '5'])
        self.table.setVerticalHeaderLabels(['1', '2', '3', '4', '5'])
        self.table.horizontalHeader().sectionDoubleClicked.connect(self.changeHorizontalHeader)

        self.button_add_c = QtWidgets.QPushButton('add column')
        self.button_add_c.clicked.connect(self.click_button_add_c)

        layout = QtWidgets.QHBoxLayout(self)
        layout.addWidget(self.table)
        layout.addWidget(self.button_add_c)

    @QtCore.pyqtSlot(int)
    def changeHorizontalHeader(self, index):
        it = self.table.horizontalHeaderItem(index)
        if it is None:
            val = self.table.model().headerData(index, QtCore.Qt.Horizontal)
            it = QtWidgets.QTableWidgetItem(str(val))
            self.table.setHorizontalHeaderItem(index, it)
        oldHeader = it.text()
        newHeader, okPressed  = QtWidgets.QInputDialog.getText(self,
            ' Change header label for column %d', "Your name:", 
            QtWidgets.QLineEdit.Normal, oldHeader)
        if okPressed:
            it.setText(newHeader)

    @QtCore.pyqtSlot()
    def click_button_add_c(self):
        culPosition = self.table.columnCount()
        self.table.insertColumn(culPosition)

if __name__ == '__main__':
    import sys
    app = QtWidgets.QApplication(sys.argv)
    main = MyWindow()
    main.show()
    sys.exit(app.exec_())