如何在python中使用pyqt在QTableWidget上添加数据(3项:N,X,Y)作为行?

2024-09-26 22:54:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我在Qtform中有一个3qlineedit和一个QTableWidget。 我想在python中使用pyqt在表中插入3个QLineEdit数据项作为一行。在

有人能给我指点方向吗?我该怎么做?在

提前谢谢。在


Tags: 方向pyqt数据项指点qtablewidgetqlineeditqtform
1条回答
网友
1楼 · 发布于 2024-09-26 22:54:43

这里的代码,3QLineEdit和aQTableWidgetQtWidget中,而不是在QtForm中,但它回答了您的问题。如果您有任何问题,请随时提出:

import sys
from PyQt4 import QtGui


class Window(QtGui.QWidget):
    def __init__(self):
        QtGui.QWidget.__init__(self)

        self.table = QtGui.QTableWidget(self)
        self.table.setRowCount(0)
        self.table.setColumnCount(3)

        self.textInput1 = QtGui.QLineEdit()
        self.textInput2 = QtGui.QLineEdit()
        self.textInput3 = QtGui.QLineEdit()

        self.button = QtGui.QPushButton("insert into table")
        self.button.clicked.connect(self.populateTable)

        layout = QtGui.QVBoxLayout(self)
        layout.addWidget(self.table)
        layout.addWidget(self.textInput1)
        layout.addWidget(self.textInput2)
        layout.addWidget(self.textInput3)
        layout.addWidget(self.button)

    def populateTable(self):

        text1 = self.textInput1.text()
        text2 = self.textInput2.text()
        text3 = self.textInput3.text()

  #EDIT - in textInput1 I've entered 152.123456
        print text1, type(text1) #152.123456 <class 'PyQt4.QtCore.QString'>
        floatToUse = float(text1) # if you need float convert QString to float like this
        print floatToUse , type(floatToUse) #152.123456 <type 'float'>
        # you can do here something with float and then convert it back to string when you're done, so you can put it in table using setItem
        backToString= "%.4f" % floatToUse # convert your float back to string so you can write it to table
        print backToString, type(backToString) #152.1235 <type 'str'>


        row = self.table.rowCount()
        self.table.insertRow(row)

        self.table.setItem(row, 0, QtGui.QTableWidgetItem(text1))
        self.table.setItem(row, 1, QtGui.QTableWidgetItem(text2))
        self.table.setItem(row, 2, QtGui.QTableWidgetItem(text3))


if __name__ == '__main__':

    app = QtGui.QApplication(sys.argv)
    window = Window()
    window.setGeometry(600, 300, 500, 500)
    window.show()
    sys.exit(app.exec_())

相关问题 更多 >

    热门问题