2014-05-08 36 views

回答

0

這裏的代碼,3 QLineEditQTableWidgetQtWidget,而不是在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_()) 
+0

非常感謝Aleksander先生。但我的imput2和imput3是一個浮點數,函數setItem只適用於字符串類型。 – Abdelmalek

+0

'stringRepresentationOfFloat =「%.4f」%yourFloatInput',其中浮點數後有4位數字。更多關於轉換浮動到字符串,你可以找到[這裏](http://stackoverflow.com/questions/15263597/python-convert-floating-point-number-to-certain-precision-then-copy-to-string) – Aleksandar

+0

你將'text1'轉換爲浮動嗎?因爲'text1'的類型是'QString' ...''self.textInput1.text()'即使你輸入了例如'152.177'也會返回'QString' ...無論如何,總是將它轉換爲字符串的方式,所以你可以使用'setItem' – Aleksandar

相關問題