ObjectA.Signal.connect(ObjectB.Slot)无法正常工作。我的理解正确吗?

时间:2019-06-18 13:26:44

标签: python pyqt5 pyside2 qfilesystemmodel

这是我对Signal and Slot的理解,对吗?

单击时,向setRootIndex()发射数据(QModelIndex)。 enter image description here

如果正确。那为什么这段代码不起作用?

username: <name>,
database_name: <db-name>,
uri: mongodb://<name>:<passwrod>@<ip1>:<port>,<ip2>:<port>,<ip3>:<port>/<db-name>?ssl=true&replicaSet=mongo<port>&ssl_ca_certs=<path-to-cert-file>,
site: <site>,
host: <ip1>:<port>,<ip2>:<port>,<ip3>:<port>,
client: None,
logger: <logging.Logger object at 0xea5b10>,
password: <password>,
port: <port>,
replica_set: mongo<port>

这是我的用户界面: enter image description here

代码:

treeView.clicked.connect(listView.setRootIndex)

1 个答案:

答案 0 :(得分:1)

执行代码时,您会收到以下消息:

QAbstractItemView::setRootIndex failed : index must be from the currently set model

该消息为我们提供了重要线索,因为QModelIndex属于某个模型,因此尽管它具有来自另一个模型的另一个QModelIndex的相同数据,但它们并不相同。

有2种可能的解决方案:

  • 仅使用一个模型
import os
from PyQt5 import QtCore, QtGui, QtWidgets

if __name__ == "__main__":
    import sys

    app = QtWidgets.QApplication(sys.argv)

    model = QtWidgets.QFileSystemModel()
    model.setRootPath(QtCore.QDir.rootPath())

    treeView = QtWidgets.QTreeView()
    treeView.setModel(model)
    treeView.setRootIndex(model.index(QtCore.QDir.homePath()))

    listView = QtWidgets.QListView()
    listView.setModel(model)
    listView.setRootIndex(model.index(QtCore.QDir.homePath()))

    treeView.clicked.connect(listView.setRootIndex)

    w = QtWidgets.QWidget()
    hlay = QtWidgets.QHBoxLayout(w)
    hlay.addWidget(treeView)
    hlay.addWidget(listView)
    w.show()

    sys.exit(app.exec_())
  • 使用初始模型的QModelIndex信息获取另一个模型的QModelIndex:
import os
from PyQt5 import QtCore, QtGui, QtWidgets

if __name__ == "__main__":
    import sys

    app = QtWidgets.QApplication(sys.argv)

    dirModel = QtWidgets.QFileSystemModel()
    dirModel.setRootPath(QtCore.QDir.rootPath())
    dirModel.setFilter(QtCore.QDir.NoDotAndDotDot | QtCore.QDir.Dirs)

    listModel = QtWidgets.QFileSystemModel()
    listModel.setRootPath(QtCore.QDir.rootPath())

    treeView = QtWidgets.QTreeView()
    treeView.setModel(dirModel)
    treeView.setRootIndex(dirModel.index(QtCore.QDir.homePath()))

    listView = QtWidgets.QListView()
    listView.setModel(listModel)
    listView.setRootIndex(listModel.index(QtCore.QDir.homePath()))

    treeView.clicked.connect(
        lambda ix: listView.setRootIndex(
            listModel.index(ix.data(QtWidgets.QFileSystemModel.FilePathRole))
        )
    )

    w = QtWidgets.QWidget()
    hlay = QtWidgets.QHBoxLayout(w)
    hlay.addWidget(treeView)
    hlay.addWidget(listView)
    w.show()

    sys.exit(app.exec_())