【发布时间】:2014-04-24 07:47:43
【问题描述】:
我希望通过QSqlQueryModel (PyqQt 5/Qt 5.2) 异步查询 SQL 数据库,这样 GUI 就不会阻塞。如何实现?也许通过多线程?请提供如何执行此操作的代码。如果异步使用 QSqlQueryModel 不实用,请随意提供替代方案(不过应该可以与 QTableView 一起使用)。
我的(同步)代码目前如下所示。主脚本 bin/app.py 加载 gui/__init__.py 并执行其main 方法。这反过来又使用gui.models.Table 从数据库中加载数据。问题是gui.models.Table同步查询数据库,同时锁定了GUI。
bin/app.py:
import os.path
import sys
sys.path.insert(0, os.path.abspath(os.path.join(
os.path.dirname(__file__), "..")))
import gui
if __name__ == "__main__":
gui.main()
gui/__init__.py:
import sys
import os.path
from PyQt5 import uic
from PyQt5 import QtCore, QtWidgets
from gui import models
class MainWindow(QtWidgets.QMainWindow):
def __init__(self):
super(MainWindow, self).__init__()
uic.loadUi(os.path.join(os.path.dirname(__file__), 'app.ui'), self)
self.tableView.setModel(models.Table(self))
def main():
app = QtWidgets.QApplication(sys.argv)
w = MainWindow()
w.show()
app.exec_()
gui/models.py:
import os.path
from PyQt5.QtCore import *
from PyQt5.QtSql import *
class Table(QSqlQueryModel):
def __init__(self, parent=None):
super(Table, self).__init__(parent)
pth = os.path.abspath(os.path.join(os.path.dirname(__file__), "..",
"test.sqlite"))
db = QSqlDatabase.addDatabase("QSQLITE")
db.setDatabaseName(pth)
if not db.open():
raise Exception("Couldn't open database '{}'".format(pth))
try:
self.setQuery("select * from Test")
finally:
db.close()
【问题讨论】:
标签: multithreading qt asynchronous pyqt qt5