QTreeView,类,参数,实例和属性

2024-10-01 15:42:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我慢慢地学会了POO、python和PyQt,在理解传递参数和属性方面遇到了一个问题。在

我在网上找到了一个处理QTreeView的代码(见下文),我不明白索引是如何传递到showPath()中的。还有为什么self.filename文件名以及文件路径.self不传递给实例?在

我希望我足够清楚。。。非常感谢。在

from PyQt4           import QtGui
class TreeViewWidget(QtGui.QWidget):
def __init__(self, parent=None):

    super(TreeViewWidget, self).__init__(parent)                
    self.model = QtGui.QFileSystemModel(self)
    self.model.setRootPath(rootpath)
    self.indexRoot = self.model.index(self.model.rootPath())

    self.treeView = QtGui.QTreeView(self)
    self.treeView.setExpandsOnDoubleClick(False)
    self.treeView.setModel(self.model)
    self.treeView.setRootIndex(self.indexRoot)
    self.treeView.setColumnWidth(0,220)
    self.treeView.clicked.connect(self.showPath)
    self.treeView.doubleClicked.connect(self.openQuickLook)

    self.labelFileName = QtGui.QLabel(self)
    self.labelFileName.setText("File Name:")

    self.lineEditFileName = QtGui.QLineEdit(self)

    self.labelFilePath = QtGui.QLabel(self)
    self.labelFilePath.setText("File Path:")

    self.lineEditFilePath = QtGui.QLineEdit(self)

    self.gridLayout = QtGui.QGridLayout()
    self.gridLayout.addWidget(self.labelFileName, 0, 0)
    self.gridLayout.addWidget(self.lineEditFileName, 0, 1)
    self.gridLayout.addWidget(self.labelFilePath, 1, 0)
    self.gridLayout.addWidget(self.lineEditFilePath, 1, 1)

    self.layout = QtGui.QVBoxLayout(self)
    self.layout.addLayout(self.gridLayout)
    self.layout.addWidget(self.treeView)

def givePathName(self, index):

    indexItem = self.model.index(index.row(), 0, index.parent())

    self.filename = self.model.fileName(indexItem)
    self.filepath = self.model.filePath(indexItem)

def showPath(self, index):

    self.givePathName(index)
    self.lineEditFileName.setText(self.filename)
    self.lineEditFilePath.setText(self.filepath)

Tags: selfindexmodeldeffilenameparenttreeviewsettext
2条回答

I don't understand how index is passed into showPath()

将小部件的单击信号显式连接到showPath

self.treeView.clicked.connect(self.showPath)

此信号的一部分是单击的特定项的index;它作为参数自动传递给showPath。在

Also why self.filename and self.filepath are not passed to the instance?

它们是实例属性,它们属于实例,并且该实例的所有方法都可以访问它们。它们在givePathName()中创建,然后是TreeViewWidget实例对象的一部分。它们以self.开头,因为按照惯例,这是在实例方法中为实例指定的名称(以及这些方法的隐式第一个参数)。在

综合起来:

^{pr2}$

QTreeView的clicked信号将所单击项的QModelIndex作为参数传递给任何连接的插槽。在

请参见Qt DocumentationPyQt signal and slots documentation。在

相关问题 更多 >

    热门问题