我想在PyQt Gui中更新我的TableView,以便隨時將新條目添加到QPSQL數據庫中,它將在Gui中的TableView中更新它。 目前,連接工作良好,並正確連接到數據庫,並顯示錶中的內容,現在只是電話簿中的名稱,電話號碼和地址列。問題是,如果我在Postgrese Sql數據庫中插入新行,除非關閉GUI並重新運行代碼,否則它不會在TableView中更新。 我只是在尋找一種方法來更新我的TableView,以便如果有東西被添加到Postrgese SQL數據庫,它會自動執行它沒有按鈕或任何東西。任何幫助表示讚賞,在此先感謝。如何在數據庫中添加新條目時更新PyQt中的TableView?
我將顯示我的代碼的一部分。
class Ui_Dialog(object):
def setupUi(self, Dialog):
Dialog.setObjectName(_fromUtf8("Dialog"))
Dialog.resize(400, 300)
self.buttonBox = QtGui.QDialogButtonBox(Dialog)
self.buttonBox.setGeometry(QtCore.QRect(30, 240, 341, 32))
self.buttonBox.setOrientation(QtCore.Qt.Horizontal)
self.buttonBox.setStandardButtons(QtGui.QDialogButtonBox.Cancel|QtGui.QDialogButtonBox.Ok)
self.buttonBox.setObjectName(_fromUtf8("buttonBox"))
self.tableView = QtGui.QTableView(Dialog)
self.tableView.setGeometry(QtCore.QRect(20, 50, 256, 192))
self.tableView.setObjectName(_fromUtf8("tableView"))
###############################數據庫 連接
db = QSqlDatabase.addDatabase("QPSQL") # Database typed set to QPSQL for postgres use
db.setDatabaseName("postgres") # This field should stay as postgres
db.setUserName("postgres") # This field should stay as postgres
db.setPassword("pass") # This field is for your personal password you used for the postgres install
db.setHostName("localhost") # This field should stay as localhost
if not db.open():
QtGui.QMessageBox.critical(None, QtGui.qApp.tr("Cannot open database"),
QtGui.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."),
QtGui.QMessageBox.Cancel)
return False
ok = db.open()
##### ##########################數據庫表添加到表視圖在主界面 #
model = QSqlTableModel()
query = QSqlQuery("SELECT * FROM PHONEBOOK", db)
model.setEditStrategy(QSqlTableModel.OnFieldChange)
model.setQuery(query)
model.submitAll()
self.tableView.setModel(model)
self.tableView.show()
model.select()
#
嗯,有趣的建議。那麼這隻會產生一個通知,說明某些事情已經添加到數據庫中,或者它會根據對數據庫的更改而物理更新GUI中的表。我正在使用的數據庫將是一個遠程數據庫,它將每隔一秒左右更新一次,並使用行和列中的新信息進行更新。所以我需要PyQt GUI能夠自動檢索數據庫中的新條目,並將它寫入GUI中的表格。這可能嗎? – Shayan
不自動。我延長了我的回答。 – Schollii
你知道我將如何在PyQt中實現一個自動更新方法,我查看了文檔,但我不確定如何在Python腳本中完成這項工作? – Shayan