将图像从 MySQL 获取到 PyQt5 中的 tableWidget [英] Getting Image from MySQL into tableWidget in PyQt5

查看:46
本文介绍了将图像从 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆