Getting Image from MySQL into tableWidget in PyQt5(将图像从 MySQL 获取到 PyQt5 中的 tableWidget)
问题描述
我已经能够从数据库中获取数据并填充到 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,所以我在这种情况下也使用它)构建一个可以转换为可以在QTableWidget中显示的QIcon的QPixmap:
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)
这篇关于将图像从 MySQL 获取到 PyQt5 中的 tableWidget的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将图像从 MySQL 获取到 PyQt5 中的 tableWidget


基础教程推荐
- oracle区分大小写的原因? 2021-01-01
- 表 './mysql/proc' 被标记为崩溃,应该修复 2022-01-01
- 如何根据该 XML 中的值更新 SQL 中的 XML 2021-01-01
- 在 MySQL 中:如何将表名作为存储过程和/或函数参数传递? 2021-01-01
- mysql选择动态行值作为列名,另一列作为值 2021-01-01
- 如何在 SQL 中将 Float 转换为 Varchar 2021-01-01
- 什么是 orradiag_<user>文件夹? 2022-01-01
- 二进制文件到 SQL 数据库 Apache Camel 2021-01-01
- MySQL 中的类型:BigInt(20) 与 Int(20) 2021-01-01
- 在多列上分布任意行 2021-01-01