Python 如何使用PySide有效地在表格小部件中插入项目?
在我的PySide应用程序中,我有一个按钮,当按下该按钮时,应用程序将连接到数据库,检索相关数据并将其插入表小部件中 我使用以下函数在表格小部件中插入项目,并使用交替的行颜色:Python 如何使用PySide有效地在表格小部件中插入项目?,python,pyside,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.iterrow
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列组成
用所有数据填充表格小部件需要几秒钟的时间。
我打算在将来为此使用一个单独的线程
有没有比我使用的更好的填充表格小部件的方法?我建议使用。也就是说,实现从
QAbtractTableModel
派生的您自己的模型,并在GUI中使用QTableView
。对于进一步的性能改进,您可以考虑用“代码> > FETCHOMENE/CONT>(请参阅)检索卡盘中的数据。我怀疑,在某个时刻,我将不得不使用QTable视图。与tablewidget相比,性能会有所提高吗?是的,即使没有fetchMore
技巧,我也希望有所提高。Qstandarditemmodel几乎与qtablewidget一样易于使用。