这是我对Signal and Slot的理解,对吗?
单击时,向setRootIndex()发射数据(QModelIndex)。
如果正确。那为什么这段代码不起作用?
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>
代码:
treeView.clicked.connect(listView.setRootIndex)
答案 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_())
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_())