问题:
在使用QTableWidget进行表格数据显示时,存在一个非常致命的问题,就是如果你的表格数据很大,那么它会在全部遍历完行和列之后才会一次性的全部显示,时间复杂度为n方。如果n非常大,常常需要等十多分钟,才能显示成功。
解决:
每遍历完一行就显示一行,并且添加进度条提示用户程序当前进度的百分比。
progressbar.py定义了一个进度条类 class progress
'''
params:
1、百分比 percentage
2、显示的文字 text
'''
from tkinter import *
pb_x = 0
pb_y = 0
pb_width = 100
pb_height = 20
pb_bg = "white"
pb_fg = "green"
pb_frame_size = 0
canvas = Canvas
class progress:
def __init__(self):
pass
# 初始化,创建Canvas实例,设定坐标和宽高
def init(self, master, x=pb_x, y=pb_y,
width=pb_width, height=pb_height,
bg=pb_bg, fg=pb_fg,
frame_size=pb_frame_size):
global pb_x
pb_x = x
global pb_y
pb_y = y
global pb_width
pb_width = width
global pb_height
pb_height = height
global pb_bg
pb_bg = bg
global pb_fg
pb_fg = fg
global pb_frame_size
pb_frame_size = frame_size
global canvas
canvas = Canvas(master, width=width, height=height, bg=pb_bg)
canvas.place(x=x, y=y)
# 运行进度条
def run(self, master, percentage, text=None):
global canvas
fill_line = canvas.create_rectangle(1.5, 1.5, 0, 23, width=0, fill=pb_fg)
canvas.coords(fill_line, (0, 0, percentage, 60))
if text:
label = Label(master, text=text)
label.place(x=pb_x + pb_width, y=pb_y)
master.update()
调用:
#实例化progress类
progressbar = progress()
root = Tk()
root.title("显示进度")
root.geometry("300x100")
progressbar.init(master=root, x=10, y=20)
input_table = df
input_table_colunms = input_table.shape[1] # 获取表格列数
input_table_header = list_array # 获取表头
self.tableWidget.setRowCount(len(input_table)) # 设置表格行数
self.tableWidget.setColumnCount(input_table_colunms) # 设置表格列数
self.tableWidget.setHorizontalHeaderLabels(input_table_header) # 给tablewidget设置行列表头
for i in range(len(input_table)):
p = int(i/len(input_table)*100)
progressbar.run(master=root, percentage=p, text="已成功显示:" + str(p) + "%")
for j in range(input_table_colunms):
x = str(input_table.iloc[i, j])
self.tableWidget.setItem(i, j, QTableWidgetItem(x)) # dataframe中的内容依次显示在表格中
root.mainloop()
print("从数据库显示解码成功")