在 PyQt5 中从 MySQL 获取图像到 tableWidget [英] Getting Image from MySQL into tableWidget in PyQt5
问题描述
我已经能够从数据库中获取数据并填充到 tableWidget,但未显示图像列.我尝试了一个我在网上找到的代码,但仍然没有用.数据库中的图像列具有 BLOB 数据类型.请协助更正我的以下代码.或者你可能想要建议和推荐 tableWidget 以外的另一种方法
I have been able to get data from database and populate into the tableWidget, but the image column is not shown. I tried a code I found online and still, it didn't work. The image column in the database has the BLOB data type. Kindly assist in correcting my following code. Or you may want to advise and recommend another method other than the tableWidget
def getPersData(self):
con = MySQLdb.connect(host="localhost", user="root", password="", database="db")
with con:
cur = con.cursor()
query = cur.execute("SELECT * FROM persons")
rows = cur.fetchall()
for row_number, row_data in enumerate(rows):
self.ui.tableWidget.insertRow(row_number)
for column_number, column_data in enumerate(row_data):
if column_number == 1:
item = self.getImg(column_data)
self.ui.tableWidget.setCellWidget(row_number, column_number, item)
else:
self.ui.tableWidget.setItem(row_number, column_number, QTableWidgetItem(str(column_data)))
self.ui.tableWidget.verticalHeader().setDefaultSectionSize(100)
self.ui.tableWidget.show()
def getImg(self, img):
img_label = self.ui.label
img_label.setText("")
img_label.setScaledContents(True)
pixmap = QPixmap()
pixmap.loadFromData(img, "PNG")
img_label.setPixmap(pixmap)
return img_label
推荐答案
使用字节的逻辑(在 我之前的答案我建议使用base64,所以我在这种情况下也使用它)构建一个QPixmap,可以转换成可以在QTableWidget中显示的QIcon:
The logic to use the bytes (in my previous answer I proposed to use base64 so I use it in this case as well) to build a QPixmap that can be converted into a QIcon that can be displayed in the QTableWidget:
for row_number, row_data in enumerate(rows):
self.ui.tableWidget.insertRow(row_number)
for column_number, column_data in enumerate(row_data):
it = QTableWidgetItem()
if column_number == 1:
pixmap = QPixmap()
pixmap.loadFromData(QByteArray.fromBase64(row_data))
icon = QIcon(pixmap)
it.setIcon(icon)
else:
it.setText(row_data)
self.ui.tableWidget.setItem(row_number, column_number, it)
这篇关于在 PyQt5 中从 MySQL 获取图像到 tableWidget的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!