【问题标题】:PySide PyQt QDataWidgetMapperPySide PyQt QDataWidgetMapper
【发布时间】:2017-02-13 20:51:14
【问题描述】:

我尝试使用 QDataWidgetMapper 将 QtGui.QPlainTextEdit 连接到模型。 我没有收到任何错误,只是在 TextEdit 中没有任何错误。 我不明白,我找不到好的示例代码。

这是一些示例代码。 我真的希望有人可以帮助我。

from PySide import QtCore, QtGui
import sys


class ComponentsListModel(QtCore.QAbstractListModel):
    def __init__(self, components=[], parent = None):
        super(ComponentsListModel, self).__init__(parent=None)
        self.components = components
        self.list = parent

    def rowCount(self, parent):
        return len(self.components)

    def data(self, index, role):
        row = index.row()

        if role == QtCore.Qt.DisplayRole:#index.isValid() and
            value = self.components[row]
            return value



class MainWindow(QtGui.QWidget):
    def __init__(self):
        super(MainWindow, self).__init__()
        self._build_ui()

    def _build_ui(self):
        self.layout = QtGui.QVBoxLayout()

        self.listView = QtGui.QListView()
        self.model = ComponentsListModel(components = ['1', '2', '3'])
        self.listView.setModel(self.model)
        self.text = QtGui.QPlainTextEdit()
        self.layout.addWidget(self.listView)
        self.layout.addWidget(self.text)
        self.setLayout(self.layout)

        self._mapper = QtGui.QDataWidgetMapper(self)
        self._mapper.setModel(self.model)
        self._mapper.setSubmitPolicy(QtGui.QDataWidgetMapper.AutoSubmit)
        self._mapper.addMapping(self.text, 0)
        self._mapper.toFirst()


if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    app.setStyle('Plastique')
    mySW = MainWindow()
    mySW.show()
    sys.exit(app.exec_())

【问题讨论】:

  • ComponentsListModel类的data函数中,尝试添加if role == Qt.EditRole: return self.components[row]
  • 像魅力一样工作,谢谢
  • 我很高兴它有帮助,我做出了回答。

标签: model-view-controller pyqt pyside


【解决方案1】:

您需要在ComponentsListModel 类中的数据函数中为Qt.EditRole 添加条件

if role == Qt.EditRole: 
        value = self.components[row]
        return value

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-02
    • 2014-03-25
    相关资源
    最近更新 更多