RError.com

RError.com Logo RError.com Logo

RError.com Navigation

  • 主页

Mobile menu

Close
  • 主页
  • 系统&网络
    • 热门问题
    • 最新问题
    • 标签
  • Ubuntu
    • 热门问题
    • 最新问题
    • 标签
  • 帮助
主页 / 问题 / 1329203
Accepted
Konstantin
Konstantin
Asked:2022-09-17 02:38:39 +0000 UTC2022-09-17 02:38:39 +0000 UTC 2022-09-17 02:38:39 +0000 UTC

如何使用数据库中的数据填充 QCombobox

  • 772

我有一个包含两个表good和category.
通过QSqlRelationalTableModel表格的可视化,用值good替换列来实现。Сategorycatnameid

按下按钮时btnAdd = QPushButton("&Добавить запись"),在数据库中实现了一条记录在一个表中good,填写时需要指明该记录属于哪个记录(以后会正常工作)。id categoryQSqlRelationalTableModel

如何代替self.line_edit_category QCombobox表格中的数据,category以便清楚用户输入的内容。

比如一个下拉列表,让用户不能输入错误的东西:

在此处输入图像描述

import sys
from PyQt5 import QtSql
from PyQt5.Qt import *


class Dialog(QDialog):
    def __init__(self):
        super().__init__()
        self.setWindowTitle('Input Dialog')
        self.line_edit_name = QLineEdit()
        self.line_edit_quantity = QLineEdit()
        self.line_edit_category = QLineEdit()

        form_layout = QFormLayout()
        form_layout.addRow('Name:', self.line_edit_name)
        form_layout.addRow('quantity:', self.line_edit_quantity)
        form_layout.addRow('category:', self.line_edit_category)

        button_box = QDialogButtonBox(
            QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        button_box.accepted.connect(self.accept)
        button_box.rejected.connect(self.reject)

        main_layout = QVBoxLayout(self)
        main_layout.addLayout(form_layout)
        main_layout.addWidget(button_box)


class Example(QMainWindow):
    def __init__(self):
        super().__init__()

        self.createConnection()
        self.fillTable()  # !!!
        self.createModel()
        self.initUI()

        self.centralWidget = QWidget()
        self.setCentralWidget(self.centralWidget)
        btnAdd = QPushButton("&Добавить запись")
        btnAdd.clicked.connect(self.addRecord)
        btnDel = QPushButton("&Удалить запись")
        btnDel.clicked.connect(self.delRecord)

        layout = QVBoxLayout(self.centralWidget)
        layout.addWidget(self.view)
        layout.addWidget(btnAdd)
        layout.addWidget(btnDel)

    def createConnection(self):
        self.db = QtSql.QSqlDatabase.addDatabase("QSQLITE")
        self.db.setDatabaseName("test_1318914.db")  # !!! .db
        if not self.db.open():
            print("Cannot establish a database connection")
            return False

    def fillTable(self):
        self.db.transaction()
        q = QtSql.QSqlQuery()
        #                             vvvvvvvv
        q.exec_("DROP TABLE IF EXISTS category;")
        q.exec_("CREATE TABLE category (id INT PRIMARY KEY, catname TEXT);")
        q.exec_("INSERT INTO category VALUES (1, 'Расходники');")
        q.exec_("INSERT INTO category VALUES (2, 'Носители');")

        #                             vvvv
        q.exec_("DROP TABLE IF EXISTS good;")
        q.exec_("CREATE TABLE good (Name TEXT, Quantity INT, Category INT);")
        q.exec_("INSERT INTO good VALUES ('Барабан для принтера', 8, 1);")
        q.exec_("INSERT INTO good VALUES ('Бумага для принтера', 3, 1);")
        q.exec_("INSERT INTO good VALUES ('Дискета', 10, 2);")
        self.db.commit()

    def createModel(self):
        self.model = QtSql.QSqlRelationalTableModel()
        self.model.setTable("good")
        self.model.setHeaderData(0, Qt.Horizontal, "Название")
        self.model.setHeaderData(1, Qt.Horizontal, "Кол-во")
        self.model.setHeaderData(2, Qt.Horizontal, "Категория")
        self.set_relation()
        self.model.select()

    def initUI(self):
        self.view = QTableView()
        self.view.setModel(self.model)
        self.view.setColumnWidth(0, 150)
        mode = QAbstractItemView.SingleSelection
        self.view.setSelectionMode(mode)

    def closeEvent(self, event):
        if (self.db.open()):
            self.db.close()

    def set_relation(self):
        self.model.setRelation(2, QtSql.QSqlRelation(
            "category",
            "id",
            "catname"
        ))

    def addRecord(self):
        inputDialog = Dialog()
        rez = inputDialog.exec()
        if not rez:
            msg = QMessageBox.information(self, 'Внимание', 'Диалог сброшен.')
            return

        name = inputDialog.line_edit_name.text()
        quantity = inputDialog.line_edit_quantity.text()
        category = inputDialog.line_edit_category.text()
        if (not name) or (not quantity) or (not category):
            msg = QMessageBox.information(self,
                                          'Внимание', 'Заполните пожалуйста все поля.')
            return

        r = self.model.record()
        r.setValue(0, name)
        r.setValue(1, int(quantity))
        r.setValue(2, int(category))

        self.model.insertRecord(-1, r)
        self.model.select()

    def delRecord(self):
        row = self.view.currentIndex().row()
        if row == -1:
            msg = QMessageBox.information(self,
                                          'Внимание', 'Выберите запись для удаления.')
            return

        name = self.model.record(row).value(0)
        quantity = self.model.record(row).value(1)
        category = self.model.record(row).value(2)

        inputDialog = Dialog()
        inputDialog.setWindowTitle('Удалить запись ???')
        inputDialog.line_edit_name.setText(name)
        inputDialog.line_edit_quantity.setText(str(quantity))
        inputDialog.line_edit_category.setText(str(category))
        rez = inputDialog.exec()
        if not rez:
            msg = QMessageBox.information(self, 'Внимание', 'Диалог сброшен.')
            return

        self.model.setRelation(2, QtSql.QSqlRelation())
        self.model.select()
        self.model.removeRow(row)
        self.set_relation()
        self.model.select()

        msg = QMessageBox.information(self, 'Успех', 'Запись удалена.')


if __name__ == '__main__':
    app = QApplication(sys.argv)
    w = Example()
    w.setWindowTitle("QRelationalSqlTableModel")
    w.resize(430, 250)
    w.show()
    sys.exit(app.exec_())
python
  • 2 2 个回答
  • 10 Views

2 个回答

  • Voted
  1. Best Answer
    S. Nick
    2022-09-17T05:16:05Z2022-09-17T05:16:05Z

    QSqlTableModel *QSqlRelationalTableModel:: relationModel(int column) const

    返回一个QSqlTableModel用于访问其列是外键的表的对象,如果此列没有关系,则返回 nullptr。

    import sys
    from PyQt5 import QtSql
    from PyQt5.Qt import *
    
    
    class Dialog(QDialog):
        def __init__(self, dict_category):                      # +++ dict_category
            super().__init__()
            self.setWindowTitle('Input Dialog')
            
            self.line_edit_name = QLineEdit()
            self.line_edit_quantity = QLineEdit()
    # !!!
    #        self.line_edit_category = QLineEdit()
            self.combobox_category = QComboBox()                              # +++
            self.combobox_category.addItems([name for name in dict_category]) # +++
    
            form_layout = QFormLayout()
            form_layout.addRow('Name:', self.line_edit_name)
            form_layout.addRow('quantity:', self.line_edit_quantity)
    # !!!
            form_layout.addRow('category:', self.combobox_category)           # +++
    
            button_box = QDialogButtonBox(
                QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
            button_box.accepted.connect(self.accept)
            button_box.rejected.connect(self.reject)
    
            main_layout = QVBoxLayout(self)
            main_layout.addLayout(form_layout)
            main_layout.addWidget(button_box)
    
    
    class Example(QMainWindow):
        def __init__(self):
            super().__init__()
    
            self.createConnection()
            self.fillTable()  # !!!
            self.createModel()
            self.initUI()
            
    # +++ vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv        
            self.model_category  = self.model.relationModel(2)   # QtSql.QSqlTableModel
            print(f'm_cat tableName == {self.model_category.tableName()}')
            print(f'm_cat rowCount  == {self.model_category.rowCount()}')
            
            self.dict_category = {}
            for row in range(self.model_category.rowCount()):
                r = self.model_category.record(row)
                id =  r.value(0) 
                name = r.value(1)
                self.dict_category[name] = id
    # +++ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    
            self.centralWidget = QWidget()
            self.setCentralWidget(self.centralWidget)
            btnAdd = QPushButton("&Добавить запись")
            btnAdd.clicked.connect(self.addRecord)
            btnDel = QPushButton("&Удалить запись")
            btnDel.clicked.connect(self.delRecord)
    
            layout = QVBoxLayout(self.centralWidget)
            layout.addWidget(self.view)
            layout.addWidget(btnAdd)
            layout.addWidget(btnDel)
    
        def createConnection(self):
            self.db = QtSql.QSqlDatabase.addDatabase("QSQLITE")
            self.db.setDatabaseName("test_1318914.db") # !!! .db
            if not self.db.open():
                print("Cannot establish a database connection")
                return False
    
        def fillTable(self):
            self.db.transaction()
            q = QtSql.QSqlQuery()
            #                             vvvvvvvv
            q.exec_("DROP TABLE IF EXISTS category;")
            q.exec_("CREATE TABLE category (id INT PRIMARY KEY, catname TEXT);")
            q.exec_("INSERT INTO category VALUES (1, 'Расходники');")
            q.exec_("INSERT INTO category VALUES (2, 'Носители');")
    
            #                             vvvv
            q.exec_("DROP TABLE IF EXISTS good;")
            q.exec_("CREATE TABLE good (Name TEXT, Quantity INT, Category INT);")
            q.exec_("INSERT INTO good VALUES ('Барабан для принтера', 8, 1);")
            q.exec_("INSERT INTO good VALUES ('Бумага для принтера', 3, 1);")
            q.exec_("INSERT INTO good VALUES ('Дискета', 10, 2);")
            self.db.commit()
    
        def createModel(self):
            self.model = QtSql.QSqlRelationalTableModel()
            self.model.setTable("good")
            self.model.setHeaderData(0, Qt.Horizontal, "Название")
            self.model.setHeaderData(1, Qt.Horizontal, "Кол-во")
            self.model.setHeaderData(2, Qt.Horizontal, "Категория")
            self.set_relation()
            self.model.select()
    
        def initUI(self):
            self.view = QTableView()
            self.view.setModel(self.model)
            self.view.setColumnWidth(0, 150)
            mode = QAbstractItemView.SingleSelection
            self.view.setSelectionMode(mode)
    
        def closeEvent(self, event):
            if (self.db.open()):
                self.db.close()
    
        def set_relation(self):
            self.model.setRelation(2, QtSql.QSqlRelation(
                "category",
                "id",
                "catname"
            ))
    
    # !!!
        def addRecord(self):
            inputDialog = Dialog(self.dict_category)      # +++ self.dict_category
            rez = inputDialog.exec()
            if not rez:
                msg = QMessageBox.information(self, 'Внимание', 'Диалог сброшен.')
                return
    
            name = inputDialog.line_edit_name.text()
            quantity = inputDialog.line_edit_quantity.text()
    # !!! combobox_category       
    #        category = inputDialog.line_edit_category.text()
            category = self.dict_category[
                inputDialog.combobox_category.currentText()
            ]
    # +++ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
            
            if (not name) or (not quantity) or (not category):
                msg = QMessageBox.information(self,
                    'Внимание', 'Заполните пожалуйста все поля.')
                return
    
            r = self.model.record()
            r.setValue(0, name)
            r.setValue(1, int(quantity))
            r.setValue(2, int(category))
    
            self.model.insertRecord(-1, r)
            self.model.select()
    
        def delRecord(self):
            row = self.view.currentIndex().row()
            if row == -1:
                msg = QMessageBox.information(self,
                    'Внимание', 'Выберите запись для удаления.')
                return
    
            name = self.model.record(row).value(0)
            quantity = self.model.record(row).value(1)
            category = self.model.record(row).value(2)
    
            inputDialog = Dialog(self.dict_category)          # +++ self.dict_category
            inputDialog.setWindowTitle('Удалить запись ???')
            inputDialog.line_edit_name.setText(name)
            inputDialog.line_edit_quantity.setText(str(quantity))
    # !!!        inputDialog.line_edit_category.setText(str(category))
    #        inputDialog.line_edit_category.setText(str(category))
            inputDialog.combobox_category.setCurrentText(str(category))  # +++
    
            rez = inputDialog.exec()
            if not rez:
                msg = QMessageBox.information(self, 'Внимание', 'Диалог сброшен.')
                return
    
            self.model.setRelation(2, QtSql.QSqlRelation())
            self.model.select()
            self.model.removeRow(row)
            self.set_relation()
            self.model.select()
    
            msg = QMessageBox.information(self, 'Успех', 'Запись удалена.')
    
    
    if __name__ == '__main__':
        app = QApplication(sys.argv)
        w = Example()
        w.setWindowTitle("QRelationalSqlTableModel")
        w.resize(430, 250)
        w.show()
        sys.exit(app.exec_())
    

    在此处输入图像描述

    • 1
  2. Konstantin
    2022-09-17T05:09:13Z2022-09-17T05:09:13Z

    总的来说,决定已经来了 =) 逻辑如下:

    1. 我们创建了一个函数,该函数将从数据库fill_combobox()中读取一个表category并返回一个格式为 ['1 Consumables', '2 Media'] 的列表,其中一个分隔符由空格分隔,以便稍后可以提取该数字以写入 id

    2. 将列表传递给对话框构造函数并填充QComboBox

    3. 我们考虑文本currentText,通过拆分我们将获取列表的第一个元素。用户感到满意和高兴 =))) 通过标记#<---的更改地点的代码 在此处输入图像描述

    import sys
    from PyQt5 import QtSql
    from PyQt5.Qt import *
    
    
    class Dialog(QDialog):
        def __init__(self, list_for_combo=[]):
            super().__init__()
            self.setWindowTitle('Input Dialog')
            self.line_edit_name = QLineEdit()
            self.line_edit_quantity = QLineEdit()
            self.q_combo_category = QComboBox() #<---
            self.q_combo_category.addItems(list_for_combo)#<---
    
            form_layout = QFormLayout()
            form_layout.addRow('Name:', self.line_edit_name)
            form_layout.addRow('quantity:', self.line_edit_quantity)
            form_layout.addRow('category:', self.q_combo_category)#<---
    
            button_box = QDialogButtonBox(
                QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
            button_box.accepted.connect(self.accept)
            button_box.rejected.connect(self.reject)
    
            main_layout = QVBoxLayout(self)
            main_layout.addLayout(form_layout)
            main_layout.addWidget(button_box)
    
    
    class Example(QMainWindow):
        def __init__(self):
            super().__init__()
    
            self.createConnection()
            self.fillTable()  # !!!
            self.createModel()
            self.initUI()
    
            self.centralWidget = QWidget()
            self.setCentralWidget(self.centralWidget)
            btnAdd = QPushButton("&Добавить запись")
            btnAdd.clicked.connect(self.addRecord)
            btnDel = QPushButton("&Удалить запись")
            btnDel.clicked.connect(self.delRecord)
    
            layout = QVBoxLayout(self.centralWidget)
            layout.addWidget(self.view)
            layout.addWidget(btnAdd)
            layout.addWidget(btnDel)
    
        def createConnection(self):
            self.db = QtSql.QSqlDatabase.addDatabase("QSQLITE")
            self.db.setDatabaseName("test_1318914.db")  # !!! .db
            if not self.db.open():
                print("Cannot establish a database connection")
                return False
    
        def fillTable(self):
            self.db.transaction()
            q = QtSql.QSqlQuery()
            #                             vvvvvvvv
            q.exec_("DROP TABLE IF EXISTS category;")
            q.exec_("CREATE TABLE category (id INT PRIMARY KEY, catname TEXT);")
            q.exec_("INSERT INTO category VALUES (1, 'Расходники');")
            q.exec_("INSERT INTO category VALUES (2, 'Носители');")
    
            #                             vvvv
            q.exec_("DROP TABLE IF EXISTS good;")
            q.exec_("CREATE TABLE good (Name TEXT, Quantity INT, Category INT);")
            q.exec_("INSERT INTO good VALUES ('Барабан для принтера', 8, 1);")
            q.exec_("INSERT INTO good VALUES ('Бумага для принтера', 3, 1);")
            q.exec_("INSERT INTO good VALUES ('Дискета', 10, 2);")
            self.db.commit()
    
        def createModel(self):
            self.model = QtSql.QSqlRelationalTableModel()
            self.model.setTable("good")
            self.model.setHeaderData(0, Qt.Horizontal, "Название")
            self.model.setHeaderData(1, Qt.Horizontal, "Кол-во")
            self.model.setHeaderData(2, Qt.Horizontal, "Категория")
            self.set_relation()
            self.model.select()
    
        def initUI(self):
            self.view = QTableView()
            self.view.setModel(self.model)
            self.view.setColumnWidth(0, 150)
            mode = QAbstractItemView.SingleSelection
            self.view.setSelectionMode(mode)
    
        def closeEvent(self, event):
            if (self.db.open()):
                self.db.close()
    
        def set_relation(self):
            self.model.setRelation(2, QtSql.QSqlRelation(
                "category",
                "id",
                "catname"
            ))
    
        def addRecord(self):
    
            def fill_combobox():#<---
                list_name = []#<---
                query = QSqlQuery('SELECT * FROM category')#<---
                while query.next():#<---
                    list_name.append(str(query.value(0))+" "+query.value(1))#<---
                query.exec_()#<---
                return list_name#<---
    
            list_name = fill_combobox()#<---
    
            inputDialog = Dialog(list_for_combo= list_name)#<---
            rez = inputDialog.exec()
            if not rez:
                msg = QMessageBox.information(self, 'Внимание', 'Диалог сброшен.')
                return
    
            name = inputDialog.line_edit_name.text()
            quantity = inputDialog.line_edit_quantity.text()
            q_combo_category = inputDialog.q_combo_category.currentText()#<---
            category = q_combo_category.split()[0]#<---
            if (not name) or (not quantity) or (not category):
                msg = QMessageBox.information(self,
                                              'Внимание', 'Заполните пожалуйста все поля.')
                return
    
            r = self.model.record()
            r.setValue(0, name)
            r.setValue(1, int(quantity))
            r.setValue(2, int(category))
    
            self.model.insertRecord(-1, r)
            self.model.select()
    
        def delRecord(self):
            row = self.view.currentIndex().row()
            if row == -1:
                msg = QMessageBox.information(self,
                                              'Внимание', 'Выберите запись для удаления.')
                return
    
            name = self.model.record(row).value(0)
            quantity = self.model.record(row).value(1)
            category = self.model.record(row).value(2)
    
            inputDialog = Dialog()
            inputDialog.setWindowTitle('Удалить запись ???')
            inputDialog.line_edit_name.setText(name)
            inputDialog.line_edit_quantity.setText(str(quantity))
            inputDialog.line_edit_category.setText(str(category))
            rez = inputDialog.exec()
            if not rez:
                msg = QMessageBox.information(self, 'Внимание', 'Диалог сброшен.')
                return
    
            self.model.setRelation(2, QtSql.QSqlRelation())
            self.model.select()
            self.model.removeRow(row)
            self.set_relation()
            self.model.select()
    
            msg = QMessageBox.information(self, 'Успех', 'Запись удалена.')
    
    
    if __name__ == '__main__':
        app = QApplication(sys.argv)
        w = Example()
        w.setWindowTitle("QRelationalSqlTableModel")
        w.resize(430, 250)
        w.show()
        sys.exit(app.exec_())
    
    • 0

相关问题

  • 是否可以以某种方式自定义 QTabWidget?

  • telebot.anihelper.ApiException 错误

  • Python。检查一个数字是否是 3 的幂。输出 无

  • 解析多个响应

  • 交换两个数组的元素,以便它们的新内容也反转

Sidebar

Stats

  • 问题 10021
  • Answers 30001
  • 最佳答案 8000
  • 用户 6900
  • 常问
  • 回答
  • Marko Smith

    表格填充不起作用

    • 2 个回答
  • Marko Smith

    提示 50/50,有两个,其中一个是正确的

    • 1 个回答
  • Marko Smith

    在 PyQt5 中停止进程

    • 1 个回答
  • Marko Smith

    我的脚本不工作

    • 1 个回答
  • Marko Smith

    在文本文件中写入和读取列表

    • 2 个回答
  • Marko Smith

    如何像屏幕截图中那样并排排列这些块?

    • 1 个回答
  • Marko Smith

    确定文本文件中每一行的字符数

    • 2 个回答
  • Marko Smith

    将接口对象传递给 JAVA 构造函数

    • 1 个回答
  • Marko Smith

    正确更新数据库中的数据

    • 1 个回答
  • Marko Smith

    Python解析不是css

    • 1 个回答
  • Martin Hope
    Alexandr_TT 2020年新年大赛! 2020-12-20 18:20:21 +0000 UTC
  • Martin Hope
    Alexandr_TT 圣诞树动画 2020-12-23 00:38:08 +0000 UTC
  • Martin Hope
    Air 究竟是什么标识了网站访问者? 2020-11-03 15:49:20 +0000 UTC
  • Martin Hope
    Qwertiy 号码显示 9223372036854775807 2020-07-11 18:16:49 +0000 UTC
  • Martin Hope
    user216109 如何为黑客设下陷阱,或充分击退攻击? 2020-05-10 02:22:52 +0000 UTC
  • Martin Hope
    Qwertiy 并变成3个无穷大 2020-11-06 07:15:57 +0000 UTC
  • Martin Hope
    koks_rs 什么是样板代码? 2020-10-27 15:43:19 +0000 UTC
  • Martin Hope
    Sirop4ik 向 git 提交发布的正确方法是什么? 2020-10-05 00:02:00 +0000 UTC
  • Martin Hope
    faoxis 为什么在这么多示例中函数都称为 foo? 2020-08-15 04:42:49 +0000 UTC
  • Martin Hope
    Pavel Mayorov 如何从事件或回调函数中返回值?或者至少等他们完成。 2020-08-11 16:49:28 +0000 UTC

热门标签

javascript python java php c# c++ html android jquery mysql

Explore

  • 主页
  • 问题
    • 热门问题
    • 最新问题
  • 标签
  • 帮助

Footer

RError.com

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

帮助

© 2023 RError.com All Rights Reserve   沪ICP备12040472号-5