PyQT5:SpinBox 值不在 qsql 中维护

PyQT5 : SpinBox values are not maintained in qsql

在一个项目上工作,我想将 spinBox 值保存在数据库中..但是代码对我不起作用..

我想要得到的结果:

比如把spinBox_1的值改成5,把spinBox_2的值改成10,程序关闭再重启的时候,一定要保持原来的值。

我有两个按钮.. 当更改 spinBox 值然后按下按钮 1 时,应保留这些值 当您按下按钮 2 时,会出现其他值并可以更改 如果程序首先重新启动,则按下按钮 1 时存储的值必须首先出现 按下按钮 2 时,应在按下按钮 2 时显示存储的值

请帮帮我

计划:

from PyQt5 import QtCore, QtGui, QtWidgets, QtSql
from PyQt5.QtSql import *
   
def create_connection(database):
    db = QtSql.QSqlDatabase.addDatabase("QSQLITE")
    db.setDatabaseName(database)
    if not db.open():
        print("Cannot open database")
        print(
            "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."
        )
        return False

    query = QtSql.QSqlQuery()
    if not query.exec_(
        """CREATE TABLE IF NOT EXISTS Devices (
    "id" INTEGER PRIMARY KEY AUTOINCREMENT,
    "floor_id" INTEGER,
    "spinBox_1" INTEGER,
    "spinBox_2" INTEGER,
    FOREIGN KEY(floor_id) REFERENCES Floors(id))"""
    ):
        print(query.lastError().text())
        return False
    return True



class Ui_Form(object):
    def setupUi(self, Form):
        Form.setObjectName("Form")
        Form.resize(267, 173)
        self.spinBox_1 = QtWidgets.QSpinBox(Form)
        self.spinBox_1.setGeometry(QtCore.QRect(60, 50, 42, 22))
        self.spinBox_1.setObjectName("spinBox_1")
        self.spinBox_2 = QtWidgets.QSpinBox(Form)
        self.spinBox_2.setGeometry(QtCore.QRect(150, 50, 42, 22))
        self.spinBox_2.setObjectName("spinBox_2")
        self.pushButton_1 = QtWidgets.QPushButton(Form)
        self.pushButton_1.setGeometry(QtCore.QRect(40, 120, 75, 23))
        self.pushButton_1.setObjectName("pushButton_1")
        self.pushButton_2 = QtWidgets.QPushButton(Form)
        self.pushButton_2.setGeometry(QtCore.QRect(140, 120, 75, 23))
        self.pushButton_2.setObjectName("pushButton_2")
        self.retranslateUi(Form)
        QtCore.QMetaObject.connectSlotsByName(Form)
        
        self.model = QtSql.QSqlQueryModel(Form)
        self.record = self.model.record(0)
        self.spinBox_1.setValue(self.record.value("spinBox_1"))
        self.spinBox_2.setValue(self.record.value("spinBox_2"))

        self.enable = True
# ----------------------------------------------------------------------------------------------
#                             if spinBox value changed
# ----------------------------------------------------------------------------------------------
        self.spinBox_1.valueChanged.connect(self.updateSpinBox_1)
        self.spinBox_2.valueChanged.connect(self.updateSpinBox_2)
# ----------------------------------------------------------------------------------------------
#                             if pushButton clicked
# ----------------------------------------------------------------------------------------------
        self.pushButton_1.clicked.connect(self.value_1)
        self.pushButton_2.clicked.connect(self.value_2)
# ----------------------------------------------------------------------------------------------
# ----------------------------------------------------------------------------------------------

    def updateSpinBox_1(self):
        if self.enable :
            self.record = self.model.record(0)
        else :
            self.record = self.model.record(1)
        self.record.setValue("spinBox_1", self.spinBox_1.value())
        self.spinBox_1.setValue(self.record.value("spinBox_1"))

        print(self.record.value("spinBox_1"))
        print(self.enable)

    def updateSpinBox_2(self):
        if self.enable :
            self.record = self.model.record(0)
        else :
            self.record = self.model.record(1)
        self.record.setValue("spinBox_2", self.spinBox_2.value())
        self.spinBox_2.setValue(self.record.value("spinBox_2"))

        print(self.record.value("spinBox_2"))
        print(self.enable)

    def value_1(self):
        self.enable = True
        self.record = self.model.record(0)
        self.spinBox_1.setValue(self.record.value("spinBox_1"))
        self.spinBox_2.setValue(self.record.value("spinBox_2"))
        return self.enable

    def value_2(self):
        self.enable = False
        self.record = self.model.record(1)
        self.spinBox_1.setValue(self.record.value("spinBox_1"))
        self.spinBox_2.setValue(self.record.value("spinBox_2"))
        return self.enable


# ----------------------------------------------------------------------------------------------
# ----------------------------------------------------------------------------------------------  
    def retranslateUi(self, Form):
        _translate = QtCore.QCoreApplication.translate
        Form.setWindowTitle(_translate("Form", "Form"))
        self.pushButton_1.setText(_translate("Form", "PushButton1"))
        self.pushButton_2.setText(_translate("Form", "PushButton2"))


if __name__ == "__main__":
    import sys
    database = "database.db"
    app = QtWidgets.QApplication(sys.argv)
    if not create_connection(database):
        sys.exit(app.exec_())
    Form = QtWidgets.QWidget()
    ui = Ui_Form()
    ui.setupUi(Form)
    Form.show()
    sys.exit(app.exec_())

首先,您使用的是 QSqlQueryModel,它是只读。作为旁注,您从未使用过 setQuery(),因此您的代码实际上不起作用,因为 self.model.record(0) 的结果是一条空记录。

那么,修改QSqlRecord的值并不意味着数据库会自动更新。

虽然您可以使用普通的 QSqlQuery 来使用标准数据库 UPDATE 命令更新值,但只要使用 QSqlTableModel,您就可以使用 QSqlRecord,为了更新数据,请调用 setRecord().请注意,由于某些与模型编辑方式相关的原因 sqlite 的工作方式,修改后的字段 generated 标志 必须 设置为 True.

class Ui_Form(object):
    def setupUi(self, Form):
        # ...
        self.model = QtSql.QSqlTableModel(Form)
        self.model.setTable('Devices')
        self.model.select()
        self.record = self.model.record(0)
        # ...

    def updateSpinBox_1(self):
        row = 0 if self.enable else 1
        self.record = self.model.record(row)
        self.record.setValue("spinBox_1", self.spinBox_1.value())
        self.spinBox_1.setValue(self.record.value("spinBox_1"))
        self.record.setGenerated('spinBox_1', True)
        self.model.setRecord(row, self.record)

注意:编辑 pyuic 生成的 .py 文件来创建程序被认为是 不好的 做法,因为这些文件应该 永不被修改;你也不应该尝试模仿他们的行为,因为他们的结构只对他们的内部使用有意义(使用来自python的ui文件)并创建UI 从代码中应该最好使用 QWidget 子类来完成。阅读有关 using Designer.

的官方 guidelines 的更多信息