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

时间:2014-05-08 09:39:28

标签: python pyqt

我在Qtform中有一个3 QLineEdit和一个QTableWidget。 我想在python中使用pyqt在表中插入3个QLineEdit数据条目。

请有人,请指点我该怎么做?

提前致谢。

1 个答案:

答案 0 :(得分:0)

此处代码3 QLineEditQTableWidget位于QtWidget,不在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_())