Python 如何使用pyqt QFileDialog将图像上载到sqllite数据库?
我正在用sqlite3数据库做一个图像查看器pyqt gui应用程序。但我无法将图像上传到数据库。我该怎么做Python 如何使用pyqt QFileDialog将图像上载到sqllite数据库?,python,python-3.x,pyqt,pyqt4,Python,Python 3.x,Pyqt,Pyqt4,我正在用sqlite3数据库做一个图像查看器pyqt gui应用程序。但我无法将图像上传到数据库。我该怎么做 def open(ui): fname = QFileDialog.getOpenFileName(ui, 'Open file','c:\\',"Image files (*.jpg *.gif)") ui.FirmEditLogoEntry.setText(fname) 我可以得到文件名。但是不能转换成二进制 请帮我做这个。 谢谢使用QFile对话框您只能获得文件名
def open(ui):
fname = QFileDialog.getOpenFileName(ui, 'Open file','c:\\',"Image files (*.jpg *.gif)")
ui.FirmEditLogoEntry.setText(fname)
我可以得到文件名。但是不能转换成二进制
请帮我做这个。
谢谢使用
QFile对话框
您只能获得文件名,您必须使用该信息读取文件的字节,然后使用QFile
并将数据保存在BLOB
s中。在下一部分中,我将展示一个示例:
import sys
from PyQt4.QtGui import *
from PyQt4.QtSql import *
from PyQt4.QtCore import *
def createConnection():
db = QSqlDatabase.addDatabase('QSQLITE')
db.setDatabaseName(':memory:')
if not db.open():
QMessageBox.critical(None, "Cannot open database",
"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.",
QMessageBox.Cancel)
return False
query = QSqlQuery()
return query.exec_('''CREATE TABLE IF NOT EXISTS imgTable
(id INTEGER primary key AUTOINCREMENT, filename TEXT, imagedata BLOB)''')
class Widget(QWidget):
def __init__(self, *args, **kwargs):
QWidget.__init__(self, *args, **kwargs)
vbox = QVBoxLayout(self)
self.load_btn = QPushButton("Select Image")
self.combo = QComboBox()
self.label = QLabel()
self.model = QSqlTableModel()
self.model.setTable("imgTable")
self.model.select()
self.combo.setModel(self.model)
self.combo.setModelColumn(1)
vbox.addWidget(self.load_btn)
vbox.addWidget(self.combo)
vbox.addWidget(self.label)
self.load_btn.clicked.connect(self.load_image)
self.combo.currentIndexChanged.connect(self.on_change_select)
def on_change_select(self, row):
ix = self.combo.model().index(row, 2)
pix = QPixmap()
pix.loadFromData(ix.data())
self.label.setPixmap(pix)
def load_image(self):
fname = QFileDialog.getOpenFileName(self, 'Open file', QDir.currentPath(), "Image files (*.jpg, *.gif, *.png)")
if fname:
self.saveImage(fname)
def saveImage(self, filename):
file = QFile(filename)
if not file.open(QIODevice.ReadOnly):
return
ba = file.readAll()
name = QFileInfo(filename).fileName()
record = self.model.record()
record.setValue("filename", name)
record.setValue("imagedata", ba)
if self.model.insertRecord(-1, record):
self.model.select()
if __name__ == '__main__':
app = QApplication(sys.argv)
if not createConnection():
sys.exit(-1)
w = Widget()
w.show()
sys.exit(app.exec_())
谢谢兄弟。。。!!这有助于我做到这一点