有一个表格,其中除了通常的信息外,还以表格形式存储了PDF文档,BLOB
以问号的形式显示如下:
如何让这些“问号”更人性化?(我想在那里放一些图标或其他东西,否则我立即期待用户的问题:“这些问号是什么?”)
最小示例(在代码文件旁边,您需要放置任何名为test_BLOB.jpg的文件,以便可以转换为BLOB
):
import sys
import os
from PySide2 import QtSql
from PySide2 import QtWidgets
from PySide2 import QtCore
class Storage_app(QtWidgets.QMainWindow):
def __init__(self, parent=None) -> None:
super().__init__()
self.createConnection()
self.fillTable() # !!! тестовое заполнение базы данных
self.createModel()
self.initUI()
self.centralWidget = QtWidgets.QWidget()
self.setCentralWidget(self.centralWidget)
layout = QtWidgets.QVBoxLayout(self.centralWidget)
layout.addWidget(self.view)
if not parent:
self.show()
def createConnection(self):
self.db = QtSql.QSqlDatabase.addDatabase("QSQLITE")
self.db.setDatabaseName("local_base.db") # !!! .db
if not self.db.open():
print("Cannot establish a database connection")
return False
def fillTable(self):
"""
Вспомогательная функция заполнениия базы данных
Отключить после тестового запуска
"""
file_path = (f"{os.getcwd()}\\test_BLOB.jpg")
test_BLOB = self.convertToBinaryData(file_path)
test_BLOB = QtCore.QByteArray(test_BLOB)
self.db.transaction()
q = QtSql.QSqlQuery()
#
q.exec_("DROP TABLE IF EXISTS company;")
q.exec_("CREATE TABLE company ("
"id INT PRIMARY KEY, "
"name_company TEXT NOT NULL, "
"blob_data BLOB NOT NULL );")
# Вставка тестовых значений
query = QtSql.QSqlQuery()
query.prepare("INSERT INTO company (id, name_company, blob_data) "
"VALUES (:id, :name_company, :blob_data)")
query.bindValue(":id", 1)
query.bindValue(":name_company", 'АО КОПЫТА')
query.bindValue(":blob_data", test_BLOB)
query.exec_()
query = QtSql.QSqlQuery()
query.prepare("INSERT INTO company (id, name_company, blob_data) "
"VALUES (:id, :name_company, :blob_data)")
query.bindValue(":id", 2)
query.bindValue(":name_company", 'АО РОГА')
query.bindValue(":blob_data", test_BLOB)
query.exec_()
self.db.commit()
def createModel(self):
"""
Создание модели для отображения
"""
self.model = QtSql.QSqlRelationalTableModel()
self.model.setTable("company")
self.model.setHeaderData(0, QtCore.Qt.Horizontal, "id")
self.model.setHeaderData(1, QtCore.Qt.Horizontal, "Наиманование")
self.model.setHeaderData(2, QtCore.Qt.Horizontal, "Документы")
self.model.select()
def initUI(self):
self.view = QtWidgets.QTableView()
self.view.setModel(self.model)
mode = QtWidgets.QAbstractItemView.SingleSelection
self.view.setSelectionMode(mode)
def closeEvent(self, event):
if (self.db.open()):
self.db.close()
def convertToBinaryData(self, file_path):
# Конвертирование в BLOB
with open(file_path, 'rb') as file:
blobData = file.read()
return blobData
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
app.setStyle('Fusion')
w = Storage_app()
app.exec_()
正如他们为我可怕的蟒蛇说对不起(我表面上认识他),但我希望你能理解..
您需要制作自定义数据模型,并覆盖所需列的 DisplayRole 以隐藏文本(问题菱形)和 DecorationRole 以显示图标
结果如下。如果你有一个 BLOB 或其他东西并不重要。通过覆盖模型,您可以做任何事情