簡體   English   中英

如何獲取文件名並將其顯示在Qlistwidget上?

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

我想通過打開QfileDialog添加文件來制作歌曲列表。
現在,當我單擊QlistWidget的項目時,可以播放list的歌曲。
但是項目名稱是其路徑。
我想在QlistWidget上顯示文件名。
當我單擊QlistWidget時,它必須將路徑轉移到openaudio()方法。

這是代碼的一部分:

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])

這是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()

順便問一下,我如何一次打開多個文件?

一種方法是將QListWidgetItem子類化:

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

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

然后將您的QListWidget連接到您的openaudio(path)方法:

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

除了該特定問題外,您的代碼似乎還有其他問題。 在這種特殊情況下,不需要使用其他列表(mlist):

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

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