如何在QTableView中使用QSqlTableModel

时间:2016-09-21 13:30:50

标签: python postgresql qt pyqt pyqt5

我的桌面视图一直空白,到目前为止,我尝试过很多东西,四处看看。我有一个小示例代码,用于学习如何在我的表视图中显示PSQL数据库中的表,似乎无法使其工作。

from PyQt5.QtSql import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
import sys
from PyQt5.uic import *

app = QApplication(sys.argv)

class ProbaTabele(QWidget):
    def __init__(self,parent = None):
        super(ProbaTabele,self).__init__(parent)

        db = QSqlDatabase.addDatabase("QPSQL")
        db.setHostName("localhost")
        db.setPort(5432)
        db.setDatabaseName("Otest")
        db.setUserName("postgres")
        db.setPassword("bizmark0")
        if (db.open() == False):
            QMessageBox.critical(None, "Database Error", db.lastError().text())
        self.db = db
        self.model = QSqlTableModel(self, self.db)
        self.model.setTable("Tabela1")
        self.model.setEditStrategy(QSqlTableModel.OnManualSubmit)
        self.model.select()
        self.model.setHeaderData(0, Qt.Horizontal, QVariant("Name"))
        self.model.setHeaderData(1, Qt.Horizontal, QVariant("Salary"))
        self.model.setHeaderData(2, Qt.Horizontal, QVariant("Horvat"))

        self.view = QTableView(self)
        self.view.setModel(self.model)

if __name__ == '__main__':
    view = ProbaTabele()
    view.show()
    sys.exit(app.exec_())

0 个答案:

没有答案