如何在Python中使用pyqt将数据(N、X、Y)作为行添加到QTableWidget?
我在一个Qt表单里有3个QLineEdit和一个QTableWidget。
我想用Python的pyqt把这3个QLineEdit里的数据作为一行插入到表格里。
有人能告诉我该怎么做吗?
谢谢!
1 个回答
0
这里有一段代码,里面有三个 QLineEdit
(就是用来输入文本的框)和一个 QTableWidget
(就是用来显示表格数据的控件),它们是在 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_())