【问题标题】:Insert blob image into QPixMap from sqlite db to QTextBrowser in PyQt5将 blob 图像插入 QPixMap 从 sqlite db 到 PyQt5 中的 QTextBrowser
【发布时间】:2019-12-31 10:00:21
【问题描述】:

我无法使用 html 标签将 qpixmap 图像插入到 qtextbrowser。 (我需要用html而不是其他方法插入)

我尝试了下面的代码。

def readImage(self):
        cur = self.db.cursor()
        covers = cur.execute("select cover from covers")
        pm = QPixmap()
        for cover in covers:
            pm.loadFromData(cover[0])
            self.ui.textBrowser.setHtml("<img src=pm /img>")

结果只是出现在 qtextbrowser 中的一个小图标,但它不显示实际图像。 请不要给我一个 qt c++ 文档页面,我看不懂那些 c++ 的东西。

【问题讨论】:

标签: python python-3.x pyqt pyqt5 qtextbrowser


【解决方案1】:

如果QtSql将返回一个可以将其编码为base64的QByteArray,则无需将数据转换为QPixmap,从而可以将图像添加到QTextEdit:

from PyQt5 import QtCore, QtGui, QtWidgets, QtSql


def create_connection(path=":memory:"):
    db = QtSql.QSqlDatabase.addDatabase("QSQLITE")
    db.setDatabaseName(path)
    if not db.open():
        QtWidgets.QMessageBox.critical(
            None,
            QtWidgets.qApp.tr("Cannot open database"),
            QtWidgets.qApp.tr(
                "Unable to establish a database connection.\n"
                "This example needs SQLite support. Please read "
                "the Qt SQL driver documentation for information "
                "how to build it.\n\n"
                "Click Cancel to exit."
            ),
            QtWidgets.QMessageBox.Cancel,
        )
        return False
    return True


class MainWindow(QtWidgets.QMainWindow):
    def __init__(self, parent=None):
        super().__init__(parent)

        self.text_edit = QtWidgets.QTextEdit()
        self.setCentralWidget(self.text_edit)

        query = QtSql.QSqlQuery("SELECT cover FROM covers")
        while query.next():
            ba = query.value(0)
            base64 = ba.toBase64().data().decode()
            self.text_edit.insertHtml(
                """<img height="200" width="200" src="data:image/png;base64,{}"/>""".format(base64)
            )
        self.resize(640, 480)


if __name__ == "__main__":
    import os
    import sys

    app = QtWidgets.QApplication(sys.argv)

    current_dir = os.path.dirname(os.path.realpath(__file__))
    path = os.path.join(current_dir, "rap.sqlite")

    if not create_connection(path):
        sys.exit(-1)

    w = MainWindow()
    w.show()
    sys.exit(app.exec_())

如果您想继续使用 sqlite3,则必须将字节转换为 QByteArray 并应用相同的逻辑:

import os
import sqlite3
from PyQt5 import QtCore, QtGui, QtWidgets


class MainWindow(QtWidgets.QMainWindow):
    def __init__(self, parent=None):
        super().__init__(parent)

        self.text_edit = QtWidgets.QTextEdit()
        self.setCentralWidget(self.text_edit)

        current_dir = os.path.dirname(os.path.realpath(__file__))
        path = os.path.join(current_dir, "rap.sqlite")

        conn = sqlite3.connect(path)
        c = conn.cursor()

        covers = c.execute("SELECT cover FROM covers")
        for cover in covers:
            data, *_ = cover
            ba = QtCore.QByteArray(data)
            base64 = ba.toBase64().data().decode()
            self.text_edit.insertHtml(
                """<img height="200" width="200" src="data:image/png;base64,{}"/>""".format(base64)
            )
        self.resize(640, 480)


if __name__ == "__main__":
    import sys

    app = QtWidgets.QApplication(sys.argv)

    w = MainWindow()
    w.show()
    sys.exit(app.exec_())

【讨论】:

  • 非常感谢您的全面回答。这是工作。有没有办法让图像适合 qtextbrowser 大小?我不想调整窗口本身的大小。 tnx.
  • @user2445398 你想改变图像的大小吗?如果是这样,你想要什么尺寸的?
  • 是的,我想在文本浏览器中显示图像时更改图像大小。我想像 200 * 200 这样的尺寸会很好。
猜你喜欢
  • 2013-03-21
  • 2013-07-30
  • 1970-01-01
  • 2020-07-25
  • 1970-01-01
  • 2013-11-02
  • 2010-11-21
  • 1970-01-01
  • 2019-06-09
相关资源
最近更新 更多