gpt4 book ai didi

python - 如何在数据库中使用 QSortFilterProxyModel?

转载 作者:太空宇宙 更新时间:2023-11-03 15:42:29 26 4
gpt4 key购买 nike

我有一个 QTableWidget,其中包含来自数据库的数据,我想实时搜索其内容(当我输入字母时,他会显示结果)?欢迎任何帮助。非常感谢。

这是我的代码:

class Filter:
def __init__(self):
object.__init__(self)
self.db = QtSql.QSqlDatabase.addDatabase('QSQLITE')
self.db.setDatabaseName("baza.db")
self.filter_model= QSortFilterProxyModel()



def sqlPodaci(self,okvir):
okvir.setObjectName("Okvir aplikacije")
okvir.resize(700,320)
line_edit = QLineEdit(okvir)
line_edit.setGeometry(20, 20, 205, 23)
self.tableWidget = QtWidgets.QTableWidget(okvir)
self.tableWidget.setGeometry(QtCore.QRect(20, 50, 620, 201))
self.tableWidget.setAlternatingRowColors(True)
self.tableWidget.setRowCount(3)
self.tableWidget.horizontalHeader().setVisible(True)
self.tableWidget.verticalHeader().setVisible(False)

###
self.filter_model.setFilterKeyColumn(1)
line_edit.textChanged.connect(self.filter_model.setFilterRegExp)
####
self.Ucitavanje_podataka()

这是从数据库读取数据的代码:

def Ucitavanje_podataka(self):

status = self.db.open()
if status == False:
QtWidgets.QMessageBox.warning(self, "Error", self.db.lastError().text(), QtWidgets.QMessageBox.Discard)
else:
self.tableWidget.setColumnCount(6)
self.tableWidget.setHorizontalHeaderLabels(['Id','Ime','Prezime','Godine','Adresa','Plata'])

row = 0
sql = " SELECT * FROM Zaposleni"
query = QtSql.QSqlQuery(sql)
while query.next():
self.tableWidget.insertRow(row)
ID=QtWidgets.QTableWidgetItem(str(query.value(0)))
Ime = QtWidgets.QTableWidgetItem(str(query.value(1)))
Prezime = QtWidgets.QTableWidgetItem(str(query.value(2)))
Godine = QtWidgets.QTableWidgetItem(str(query.value(3)))
Adresa = QtWidgets.QTableWidgetItem(str(query.value(4)))
Plata = QtWidgets.QTableWidgetItem(str(query.value(5)))

self.tableWidget.setItem(row,0,ID)
self.tableWidget.setItem(row, 1, Ime)
self.tableWidget.setItem(row, 2, Prezime)
self.tableWidget.setItem(row, 3, Godine)
self.tableWidget.setItem(row, 4, Adresa)
self.tableWidget.setItem(row, 5, Plata)
row=row+1

最佳答案

QTableWidget 有一个无法替换的预设模型,所以使用 QSortFilterProxyModel 是不可能的,所以你应该使用 QTableView,一个可能的解决方案对于过滤的主要问题是仅使用 QSqlQueryModel 并使用 LIKE 命令进行过滤。

from PyQt5 import QtWidgets, QtSql

def createConnection():
db = QtSql.QSqlDatabase.addDatabase("QSQLITE")
db.setDatabaseName("baza.db")
if not db.open():
QtWidgets.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.", QtWidgets.QMessageBox.Cancel)
return False
return True

class Widget(QtWidgets.QWidget):
def __init__(self, parent=None):
super(Widget, self).__init__(parent)
lay = QtWidgets.QVBoxLayout(self)
lineEdit = QtWidgets.QLineEdit()
tableView = QtWidgets.QTableView()
lay.addWidget(lineEdit)
lay.addWidget(tableView)
lineEdit.textChanged.connect(self.onTextChanged)

self.model = QtSql.QSqlQueryModel()
tableView.setModel(self.model)
self.onTextChanged("")

def onTextChanged(self, text):
query = QtSql.QSqlQuery()
query.prepare("SELECT * FROM Zaposleni WHERE Ime LIKE ?")
query.addBindValue("{}%".format(text))
query.exec_()
self.model.setQuery(query)


if __name__ == '__main__':
import sys

app = QtWidgets.QApplication(sys.argv)
if not createConnection():
sys.exit(-1)
w = Widget()
w.show()
sys.exit(app.exec_())

在前面的示例中,我们希望单词以 QLineEdit 的文本开头,如果您想查找它是否包含您必须将其替换为的单词:

query.addBindValue("%{}%".format(text))

如果你仍然想使用QSortFilterProxyModel,你可以看下面的例子:

from PyQt5 import QtCore, QtWidgets, QtSql

def createConnection():
db = QtSql.QSqlDatabase.addDatabase("QSQLITE")
db.setDatabaseName("baza.db")
if not db.open():
QtWidgets.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.", QtWidgets.QMessageBox.Cancel)
return False
return True

class Widget(QtWidgets.QWidget):
def __init__(self, parent=None):
super(Widget, self).__init__(parent)
lay = QtWidgets.QVBoxLayout(self)
lineEdit = QtWidgets.QLineEdit()
tableView = QtWidgets.QTableView()
lay.addWidget(lineEdit)
lay.addWidget(tableView)
lineEdit.textChanged.connect(self.onTextChanged)

self.model = QtSql.QSqlQueryModel()
self.model.setQuery("SELECT * FROM Zaposleni")

self.proxy = QtCore.QSortFilterProxyModel()
self.proxy.setSourceModel(self.model)
self.proxy.setFilterKeyColumn(1)

tableView.setModel(self.proxy)

def onTextChanged(self, text):
regex = "^{}".format(text)
self.proxy.setFilterRegExp(QtCore.QRegExp(regex, QtCore.Qt.CaseInsensitive))


if __name__ == '__main__':
import sys

app = QtWidgets.QApplication(sys.argv)
if not createConnection():
sys.exit(-1)
w = Widget()
w.show()
sys.exit(app.exec_())

在前面的示例中,我们希望单词以 QLineEdit 的文本开头,如果您想查找它是否包含您必须将其替换为的单词:

regex = "[{}]".format(text) if text else ""

关于python - 如何在数据库中使用 QSortFilterProxyModel?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51787219/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com