代码
'''
对QTableWidget表格进行数据绑定
'''
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QFileDialog
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(500, 300)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.tableWidget = QtWidgets.QTableWidget(self.centralwidget)
self.tableWidget.setGeometry(QtCore.QRect(0, 40, 501, 270))
self.tableWidget.setObjectName("tableWidget")
self.tableWidget.setColumnCount(2)
self.tableWidget.setRowCount(0)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setHorizontalHeaderItem(0, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setHorizontalHeaderItem(1, item)
self.tableWidget.setColumnWidth(0, 180)
self.pushButton = QtWidgets.QPushButton(self.centralwidget)
self.pushButton.setGeometry(QtCore.QRect(10, 10, 75, 23))
font = QtGui.QFont()
font.setPointSize(10)
font.setBold(True)
font.setWeight(75)
self.pushButton.setFont(font)
self.pushButton.setObjectName("pushButton")
MainWindow.setCentralWidget(self.centralwidget)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "对QTableWidget表格进行数据绑定"))
item = self.tableWidget.horizontalHeaderItem(0)
item.setText(_translate("MainWindow", "文件名"))
item = self.tableWidget.horizontalHeaderItem(1)
item.setText(_translate("MainWindow", "文件大小"))
self.pushButton.setText(_translate("MainWindow", "选择路径"))
self.pushButton.clicked.connect(self.bindTable)
def bindTable(self):
try:
import os
self.dir_path = QFileDialog.getExistingDirectory(None, "选择路径", os.getcwd())
self.list = os.listdir(self.dir_path)
flag=0
for i in range(0, len(self.list)):
filepath = os.path.join(self.dir_path, self.list[i])
if os.path.isfile(filepath):
self.tableWidget.insertRow(flag)
self.tableWidget.setItem(flag, 0, QtWidgets.QTableWidgetItem(self.list[i]))
fileinfo=os.stat(filepath)
self.tableWidget.setItem(flag, 1, QtWidgets.QTableWidgetItem(str(fileinfo.st_size)+' B'))
flag+=1
except Exception as e:
print(e)
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_())
效果