首页 > 解决方案 > 使用 QLineEdit 更改 QTableWidget 标题标签

问题描述

所以我在 QtDesigner 中制作了一个表格,我想使用 QLineEdit.text() 来命名它的标题。

QLineEdit 将用方括号 [] 表示。QPushButton 将用大括号{}表示。

列名:[ placeholdertext ] { Name}

我正在使用QspinBox索引。

现在我想要的是give the user the possibility of naming all columns简单by typing [First_name, Last_name, Id_Number, ...]i dont know how to name the headers既不怎么使用这个split东西

我怎样才能做到这一点?

更新 :

在此处输入图像描述

def NameHeaders(self):
    colpos = self.ColumnSpinBox.value()
    colname = self.nameColumnLineEdit.text()
    model = QtGui.QStandardItemModel()
    model.setVerticalHeaderLabels(colname, split(","))
    self.TableWidget.setModel(model)

这是我创建的链接到的功能

"Name column/Row" Button

(现在它只关注命名列而不是行),

所以我想要的是通过在列 QlineEdit 中键入类似以下内容来命名列:First_name、Last_name、Id_number、...

我希望代码检测逗号之间的文本并将每个文本分配给 QSpinBox 的值

例子 :

QSpinBoxValue: 2 || Column name : First_name, Last_name, id_number


On_Click 'Name Column/Row' Button: 


assign First_name to Header with index 0


assign Last_name to header with index 1


assign Id_Number to header with index 2

我的例子清楚吗?

标签: pythonpyqtpyqt5qtablewidget

解决方案


当您想QSpinBox用逗号之间textChangedQLineEdit单词数更新QSpinBox. 要设置标题中的文本,您必须使用setHorizontalHeaderLabels(),但在此之前,您必须在必要时更改列数。

from PyQt5 import QtCore, QtWidgets


class Widget(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super(Widget, self).__init__(parent)
        self.table_widget = QtWidgets.QTableWidget(4, 6)
        self.spinbox = QtWidgets.QSpinBox()
        self.le = QtWidgets.QLineEdit()
        self.le.textChanged.connect(self.on_textChanged)
        button = QtWidgets.QPushButton("Change")
        button.clicked.connect(self.on_clicked)

        lay = QtWidgets.QVBoxLayout(self)
        hlay = QtWidgets.QHBoxLayout()
        hlay.addWidget(self.spinbox)
        hlay.addWidget(self.le)
        hlay.addWidget(button)
        lay.addWidget(self.table_widget)
        lay.addLayout(hlay)

    @QtCore.pyqtSlot(str)
    def on_textChanged(self, text):
        words = text.split(",")
        n_words = len(words)
        self.spinbox.setValue(n_words)

    @QtCore.pyqtSlot()
    def on_clicked(self):
        words = self.le.text().split(",")
        n_words = len(words)
        if n_words > self.table_widget.columnCount():
            self.table_widget.setColumnCount(n_words)
        self.table_widget.setHorizontalHeaderLabels(words)


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

推荐阅读