如何使用PySide高效地在表格小部件中插入项目?

时间:2016-04-17 16:03:07

标签: python pyside

在我的PySide应用程序中,我有一个按钮,当按下应用程序连接到数据库时,检索相关数据并将它们插入到表格小部件中。

我使用以下函数在表格小部件中插入项目,使用交替的行颜色:

def insert_data_to_table_widget(self, data, cols, table_widget):
    """ Insert items to table widget"""
    data = data[cols]
    for row_n, row in data.iterrows():
        table_widget.insertRow(row_n)
        status = row["Status"]
        for col_n, row_item in enumerate(row.iteritems()):
            item_value = row_item[1]
            item = QtGui.QTableWidgetItem()
            item.setText(QtGui.QApplication.translate("Dialog", str(item_value),
                                                      None, QtGui.QApplication.UnicodeUTF8))
            item.setTextAlignment(QtCore.Qt.AlignHCenter|QtCore.Qt.AlignVCenter|QtCore.Qt.AlignCenter)
            font = QtGui.QFont()
            font.setFamily("Segoe UI Light")
            font.setPointSize(12)
            font.setBold(False)
            font.setWeight(50)
            item.setFont(font)

            # Background color based on result
            background_colors = {"New": (255, 255, 255),
                                 "Won": (0, 170, 0),
                                 "Lost": (170, 0, 0)}
            if col_n == 0:
                try:
                    background_color = background_colors[status]
                except Exception as e:
                    # print "status not in dictionary":, e
                    background_color = (0, 0, 0)

                background_brush = QtGui.QBrush(QtGui.QColor(*background_color))
                background_brush.setStyle(QtCore.Qt.SolidPattern)
                item.setBackground(background_brush)

            # Change foreground color
            if row_n % 2 != 0:  # Odd rows
                foreground_brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
            else:  # Even rows
                foreground_brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))

            if col_n == 0:  # First column with number
                if status == "New":
                    foreground_brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
                else:
                    foreground_brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))

            foreground_brush.setStyle(QtCore.Qt.NoBrush)
            item.setForeground(foreground_brush)    

            table_widget.setItem(row_n, col_n, item)

    table_widget.resizeColumnsToContents()
    self.resize_table_widget_columns(table_widget)

我的数据包含9000行,目前有20列。

用所有数据填充表格小部件需要几秒钟。 我打算将来使用一个单独的线程。

有没有比我使用的更好的方法来填充表格小部件?

0 个答案:

没有答案