用列表加载Qtablewidget

时间:2019-02-14 13:31:23

标签: python pyqt5

我有一个如下列表

[('John', datetime.datetime(2019, 5, 5, 0, 54), datetime.datetime(2019, 5, 26, 22, 51, 36)),
('Rex', datetime.datetime(2019, 5, 26, 22, 51, 36), datetime.datetime(2019, 6, 15, 10, 22, 48)),
('Watson', datetime.datetime(2019, 6, 15, 10, 22, 48), datetime.datetime(2019, 7, 8, 13, 33, 36)), 
('Manila', datetime.datetime(2019, 7, 8, 13, 33, 36), datetime.datetime(2019, 7, 29, 6, 18)), 
('Pete', datetime.datetime(2019, 7, 29, 6, 18), datetime.datetime(2019, 8, 6, 18, 50, 24)), 
('Mathew', datetime.datetime(2019, 8, 6, 18, 50, 24), datetime.datetime(2019, 8, 31, 3, 14, 24))]

我创建了一个如下所示的UI Qtablewidget

如何在Name列中添加名称,在From列中添加第一个日期,在To列中添加第二个日期。我在按钮点击上尝试了setitem,但没有成功

from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
    import datetime
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(800, 600)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.tableWidget = QtWidgets.QTableWidget(self.centralwidget)
        self.tableWidget.setGeometry(QtCore.QRect(30, 90, 311, 301))
        self.tableWidget.setObjectName("tableWidget")
        self.tableWidget.setColumnCount(3)
        self.tableWidget.setRowCount(0)
        item = QtWidgets.QTableWidgetItem()
        self.tableWidget.setHorizontalHeaderItem(0, item)
        item = QtWidgets.QTableWidgetItem()
        self.tableWidget.setHorizontalHeaderItem(1, item)
        item = QtWidgets.QTableWidgetItem()
        self.tableWidget.setHorizontalHeaderItem(2, item)
        self.pushButton = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton.setGeometry(QtCore.QRect(240, 430, 75, 23))
        self.pushButton.setObjectName("pushButton")
        MainWindow.setCentralWidget(self.centralwidget)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        item = self.tableWidget.horizontalHeaderItem(0)
        item.setText(_translate("MainWindow", "Name"))
        item = self.tableWidget.horizontalHeaderItem(1)
        item.setText(_translate("MainWindow", "From"))
        item = self.tableWidget.horizontalHeaderItem(2)
        item.setText(_translate("MainWindow", "To"))
        self.pushButton.setText(_translate("MainWindow", "Load"))
        self.pushButton.clicked.connect(self.onload)
    def onload(self):
        for i in mainlist:
            self.tableWidget.setItem(i[1])


if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())

我该如何做

1 个答案:

答案 0 :(得分:0)

基本上就像使用2D阵列

  • 获取数据的行数和列数:

    numcols = len(data[0])   # ( to get number of columns, count number of values in first row( first row is data[0]))
    
    numrows = len(data)   # (to get number of rows, count number of values(which are arrays) in data(2D array))
    
  • 设置QTableWidget的尺寸:

    self.tableWidget.setColumnCount(numcols)
    
    self.tableWidget.setRowCount(numrows)
    
  • 使用基本的nasted for循环传递数据(2D数组): 在每一步中,将数据(二维数组)中的值设置为QTableWidget中的相同位置:

    self.tableWidget.setItem(row, column, QTableWidgetItem((data[row][column])))
    

    其中:

    • 行,列= QTableWidget中的索引

    • QTableWidgetItem((data [row] [column])))=您将在QTableWidget中设置的值

注释: QTableWidgetItem(const QString&text)

QTableWidgetItem类提供了与QTableWidget类一起使用的项目

注意:您不能将datetime传递给QTableWidgetItem,因为您需要检查要设置为QTableWidget的值是否为datetime,如果是,则需要将datetime转换为字符串:

if isinstance(data[row][column], datetime.datetime):

     ...data[row][column].strftime('%d/%m/%Y %H:%M:%S')

完整代码:

    from PyQt5.QtWidgets import QTableWidgetItem
    from datetime import datetime
    import datetime

    data = [('John', datetime.datetime(2019, 5, 5, 0, 54), datetime.datetime(2019, 5, 26, 22, 51, 36)),
    ('Rex', datetime.datetime(2019, 5, 26, 22, 51, 36), datetime.datetime(2019, 6, 15, 10, 22, 48)),
    ('Watson', datetime.datetime(2019, 6, 15, 10, 22, 48), datetime.datetime(2019, 7, 8, 13, 33, 36)),
    ('Manila', datetime.datetime(2019, 7, 8, 13, 33, 36), datetime.datetime(2019, 7, 29, 6, 18)),
    ('Pete', datetime.datetime(2019, 7, 29, 6, 18), datetime.datetime(2019, 8, 6, 18, 50, 24)),
    ('Mathew', datetime.datetime(2019, 8, 6, 18, 50, 24), datetime.datetime(2019, 8, 31, 3, 14, 24))]

    numrows = len(data)  # 6 rows in your example
    numcols = len(data[0])  # 3 columns in your example

    # Set colums and rows in QTableWidget
    self.tableWidget.setColumnCount(numcols)
    self.tableWidget.setRowCount(numrows)

    # Loops to add values into QTableWidget
    for row in range(numrows):
        for column in range(numcols):
            # Check if value datatime, if True convert to string 
            if isinstance(data[row][column], datetime.datetime):
                self.tableWidget.setItem(row, column, QTableWidgetItem((data[row][column].strftime('%d/%m/%Y %H:%M:%S'))))
            else:
                self.tableWidget.setItem(row, column, QTableWidgetItem((data[row][column])))

结果: enter image description here