当setOrientation为Vertical时,QDataWidgetMapper无法与PyQt中的QSqlTableModel一起正常工作

时间:2012-11-16 12:31:00

标签: pyqt qsqltablemodel setorientation

我有一个奇怪的问题。如果我只将两个小部件映射到SQLITE表的前两行(“simpletable”),则以下代码可以正常工作。小部件在启动时填充,当我编辑小部件并单击按钮并调用mapper.submit()时,表格会正确更新。

但是,只要我映射第三个窗口小部件,窗口小部件值在启动时就会正确填充,但是在调用mapper.submit()并且没有映射工作时我会收到错误。

“simpletable”只是一组简单的行和列,带有文本值:

"simpletable"
a1 b1 c1 d1
a2 b2 c2 d2
a3 b3 c3 d3

当方向设置为水平时,列已正确映射,一切正常。对问题可能有什么建议?

from PyQt4 import QtGui, QtCore, QtSql
import sys

def mapValues(mapper):
    if not mapper.submit():
        print "error!"
    else:
        print "ok!"
    mapper.toFirst()

if __name__ == '__main__':

    app = QtGui.QApplication(sys.argv)
    mw = QtGui.QWidget()
    db = QtSql.QSqlDatabase.addDatabase("QSQLITE")
    db.setDatabaseName("demo_mapper.db")
    if not db.open():
        print "did not open"
    model = QtSql.QSqlTableModel()
    model.setTable("simpletable")
    model.select()
    model.submitAll()

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

    mapper = QtGui.QDataWidgetMapper()
    mapper.setSubmitPolicy(QtGui.QDataWidgetMapper.ManualSubmit)
    mapper.setModel(model)
    mapper.setOrientation(QtCore.Qt.Vertical)
    mapper.setCurrentIndex(0)

    vbox = QtGui.QVBoxLayout()
    vbox.addWidget(view)

    qlinePropValue_0 = QtGui.QLineEdit()
    qlinePropValue_1 = QtGui.QLineEdit()
    qlinePropValue_2 = QtGui.QLineEdit()

    mapper.addMapping(qlinePropValue_0, 0)
    mapper.addMapping(qlinePropValue_1, 1)

    ### ERROR HAPPENS IF LINE BELOW IS INCLUDED ###
    ### NO ERROR IF LINE BELOW IS COMMENTED OUT
    mapper.addMapping(qlinePropValue_2, 2)

    mapper.toFirst()

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

    vbox.addWidget(qlinePropValue_0)
    vbox.addWidget(qlinePropValue_1)
    vbox.addWidget(qlinePropValue_2)

    mybutton = QtGui.QPushButton()
    mybutton.setText("Press Me")
    mybutton.clicked.connect(lambda: mapValues(mapper))
    vbox.addWidget(mybutton)

    mw.setLayout(vbox)
    mw.show()

    sys.exit(app.exec_())

0 个答案:

没有答案