简体   繁体   English

如何获取文件名并将其显示在Qlistwidget上?

[英]How to get the file name and show it on Qlistwidget?

I want to make a song list by open the QfileDialog to add the file . 我想通过打开QfileDialog添加文件来制作歌曲列表。
Now I can play the song of list , When I click the item of QlistWidget. 现在,当我单击QlistWidget的项目时,可以播放list的歌曲。
But the item name is its path . 但是项目名称是其路径。
I want to show the file name on QlistWidget . 我想在QlistWidget上显示文件名。
And when I click the item of QlistWidget , it has to transfer the path to openaudio() method . 当我单击QlistWidget时,它必须将路径转移到openaudio()方法。

Here is part of code : 这是代码的一部分:

expand='Image Files(*.mp3 *.wav)'
tips=open the file''
path = QtGui.QFileDialog.getOpenFileName(self, tips,QtGui.QDesktopServices.storageLocation(QtGui.QDesktopServices.MusicLocation), expand)
if path:
   mlist.append(path)
   index=mlist.index(path) 
   self.ui.listWidget.insertItem(index,mlist[index])

Here is code of openaudio() : 这是openaudio()的代码:

def openaudio(self,path):
        self.connect(self.ui.listWidget,QtCore.SIGNAL('currentTextChanged(QString)'),self.ui.label_4,QtCore.SLOT('setText(QString)'))
        index=self.ui.listWidget.currentRow()        
        path=mlist[index]

        self.mediaObject.setCurrentSource(phonon.Phonon.MediaSource(path))
        self.mediaObject.play()

By the way ,how can I open multiple files at once ? 顺便问一下,我如何一次打开多个文件?

One way would be subclassing QListWidgetItem : 一种方法是将QListWidgetItem子类化:

class MyItem(QListWidgetItem):
    def __init__(self, path, parent=None):
        self.path = path

        import os
        filename = os.path.basename(self.path)
        super().__init__(filename)

And then connecting your QListWidget to your openaudio(path) method: 然后将您的QListWidget连接到您的openaudio(path)方法:

self.ui.listWidget.itemClicked.connect(lambda n: openaudio(n.path))

Apart from that specific question your code seems to have some other issues. 除了该特定问题外,您的代码似乎还有其他问题。 Using an additional list (mlist) is not needed in this particular case: 在这种特殊情况下,不需要使用其他列表(mlist):

path = QtGui.QFileDialog.getOpenFileName(self, tips, QtGui.QDesktopServices.storageLocation(QtGui.QDesktopServices.MusicLocation), expand)
if path:
    self.ui.listWidget.addItem(MyItem(path))

and

def openaudio(self, path):
    # Do not do this here! Connections should usually be made in the init() method of the container!
    # self.connect(self.ui.listWidget,QtCore.SIGNAL('currentTextChanged(QString)'),self.ui.label_4,QtCore.SLOT('setText(QString)'))

    # Also take a look at the 'new' PyQt signals & slots style:
    # self.ui.listWidget.currentTextChanged.connect(self.ui.label_4.setText)

    self.mediaObject.setCurrentSource(phonon.Phonon.MediaSource(path))
    self.mediaObject.play()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM