python - 使用 QLineEdit 更改 QTableWidget 标题标签

标签 python pyqt pyqt5 qtablewidget

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

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

列名称:[placeholdertext] {名称}

我使用 QspinBox 作为索引。

现在我想要的是为用户提供命名所有列的可能性只需通过键入 [First_name, Last_name, Id_Number, ...] 但是我不知道如何命名 header 也不知道如何使用split东西

我怎样才能做到这一点?

更新:

enter image description here

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

我的例子清楚吗?

最佳答案

当您想要使用逗号之间的单词数更新 QSpinBox 时,第一件事是使用 QLineEdittextChanged 信号,这样每次文本更改时它都会发出通知,分隔单词,对它们进行计数并更新QSpinBox。要设置标题中的文本,您必须使用 setHorizo​​ntalHeaderLabels(),但在此之前,您必须根据需要更改列数。

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_())

关于python - 使用 QLineEdit 更改 QTableWidget 标题标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53024538/

相关文章:

javascript - 数组作为默认参数在 Javascript 中安全吗?

python - PyQt4:按包含图标的列对 QTableWidget 进行排序

python - PyQt:表单布局内的 QLineEdit 小部件放置

python - 如何使背景颜色与表单背景颜色相同?

python - PyQt5,多种颜色的Qlabel文本

python - PyQt5:用表格小部件中的项目填充组合框

python - 如何将Python连接到SQL Azure?

python - 获取二维数组中每列的第二个最小值

python - UDP数据包加密

SELECT/WHERE 中的 python SQL 变量