使用pyqt和qtsql构建主/详细信息表单

时间:2015-12-10 22:55:49

标签: python qt pyqt qtsql qsqltablemodel

修改:重新发布新代码并清除问题: 在下面的代码中,您可以正确添加和保存,问题是: 我需要做同样的事情,但没有在行更改时向数据库提交数据,我需要能够添加新的联系人记录(主)并将电话插入表(详细信息)而不提交每个记录我插入并仅在单击保存时提交

-------------旧问题-------------------

我想创建一个表单来显示使用QtSql和PyQt的主/详细数据,所以下面的代码是我想要做的样本, 我需要能够在联系人下插入新手机并保存

我读过“使用Python和Qt进行快速GUI编程”这本书,但没有找到怎么做,所以我发布了这个问题的完整工作示例,我需要修改它以按需工作

编辑:其实我不知道为什么要投票?,问题不明确吗?

import sys
from PySide.QtGui import *
from PySide.QtSql import *


class MainWidget(QWidget):

    def __init__(self):
        QWidget.__init__(self)
        self.setWindowTitle("Address Book Example")
        self.initUI()
        db = QSqlDatabase.addDatabase("QSQLITE")
        db.setDatabaseName("addressbook.db")
        ok = db.open()

        self.contacts_model = QSqlTableModel()
        self.contacts_model.setTable('contacts')
        self.contacts_model.setEditStrategy(QSqlTableModel.OnFieldChange)
        self.contacts_model.select()

        self.phones_model = QSqlRelationalTableModel()
        self.phones_model.setTable('phones')
        self.phones_model.setEditStrategy(QSqlTableModel.OnRowChange)
        self.phones_model.setRelation(1, QSqlRelation('contacts', 'id', 'full_name'))
        self.phones_model.select()

        self.conatacts_mapper = QDataWidgetMapper()
        self.conatacts_mapper.setModel(self.contacts_model)
        self.conatacts_mapper.addMapping(self.txtFullName, 1)
        self.conatacts_mapper.addMapping(self.txtAddress, 2)
        self.conatacts_mapper.toFirst()
        self.record_changed()

        self.tblPhones.setModel(self.phones_model)
        # self.tblPhones.setColumnHidden(0, True)
        # self.tblPhones.setColumnHidden(1, True)

        self.btnNext.clicked.connect(self.conatacts_mapper.toNext)
        self.btnPrev.clicked.connect(self.conatacts_mapper.toPrevious)
        self.btnAdd.clicked.connect(self.add_record)
        self.btSave.clicked.connect(self.save)
        self.btNew.clicked.connect(self.new_contact)
        self.conatacts_mapper.currentIndexChanged.connect(self.record_changed)

    def add_record(self):
        if self.phones_model.rowCount() == 0:
            index = self.conatacts_mapper.currentIndex()
            self.conatacts_mapper.submit()
            self.conatacts_mapper.setCurrentIndex(index)
            self.prepare_sub()
        row = self.phones_model.rowCount()
        self.phones_model.insertRow(row)
        index = self.phones_model.index(row, 1)
        self.tblPhones.setCurrentIndex(index)
        self.tblPhones.edit(index)
        self.phones_model.setData(self.phones_model.index(self.phones_model.rowCount() - 1, 1),
                                  self.contacts_model.record(self.conatacts_mapper.currentIndex()).value('id'))

    def record_changed(self):
        self.phones_model.setFilter("contact_id = {}".format(self.conatacts_mapper.currentIndex()+1))

    def save(self):
        self.contacts_model.submitAll()
        self.phones_model.submitAll()
        self.conatacts_mapper.submit()

    def new_contact(self):
        self.contacts_model.insertRow(self.contacts_model.rowCount())
        self.conatacts_mapper.setCurrentIndex(self.contacts_model.rowCount() - 1)

    def prepare_sub(self):
        self.phones_model.setTable('phones')
        self.phones_model.setRelation(1, QSqlRelation('contacts', 'id', 'full_name'))
        self.phones_model.select()
        self.phones_model.setFilter('contact_id=%s' % self.contacts_model.record(self.conatacts_mapper.currentIndex()).value('id'))

    def initUI(self):
        main_layout = QHBoxLayout()
        right_layout = QVBoxLayout()
        left_layout = QVBoxLayout()

        main_layout.addLayout(right_layout)
        main_layout.addLayout(left_layout)

        name_label = QLabel("Full Name")
        self.txtFullName = QLineEdit()
        address_label = QLabel("Address")
        self.txtAddress = QLineEdit()
        phones_label = QLabel("Phone Numbers")
        self.tblPhones = QTableView()

        right_layout.addWidget(name_label)
        right_layout.addWidget(self.txtFullName)
        right_layout.addWidget(address_label)
        right_layout.addWidget(self.txtAddress)

        right_layout.addWidget(phones_label)
        right_layout.addWidget(self.tblPhones)

        self.btnPrev = QPushButton("Previous")
        self.btnNext = QPushButton("Next")
        self.btnAdd = QPushButton("Add")
        self.btSave = QPushButton('Save')
        self.btNew = QPushButton('New')

        left_layout.addWidget(self.btNew)
        left_layout.addWidget(self.btnPrev)
        left_layout.addWidget(self.btnNext)
        left_layout.addStretch(1)
        left_layout.addWidget(self.btnAdd)
        left_layout.addWidget(self.btSave)

        self.setLayout(main_layout)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    w = MainWidget()
    w.show()
    sys.exit(app.exec_())

1 个答案:

答案 0 :(得分:0)

您需要在新行中设置外键列“contact_id”的值。

我已按以下方式更新您的代码:

1-添加新字段以保存联系人ID并添加到布局

    id_label = QLabel("Id")
    self.txtId = QLineEdit()
    self.txtId.setReadOnly(True)
    #....

    right_layout.addWidget(id_label)
    right_layout.addWidget(self.txtId)

2-更新映射以填充txtId

    self.conatacts_mapper.addMapping(self.txtId, 0)

3-更新add_record方法以填写手机型号中的contact_id

 def add_record(self):
    indexModel = self.phones_model.rowCount()
    self.phones_model.insertRow(indexModel)
    self.phones_model.setData(self.phones_model.index(indexModel,1),self.txtId.text())