pyside获取目录?

时间:2014-03-12 20:30:53

标签: python directory pyside

如何在用户从“浏览...”中选择目录后,从中选择目录。按钮?我的目标是使用项目字段中的名称在该目录中创建一个文件夹。这个目录的选择'是我需要帮助搞清楚的最后一部分。谢谢你们。

import sys
import os
from PySide import QtGui

class Example(QtGui.QWidget):

    def __init__(self):
        super(Example, self).__init__()

        self.initUI()

    def initUI(self):

        QtGui.QToolTip.setFont(QtGui.QFont('SansSerif', 10))

        self.setToolTip('This is a <b>QWidget</b> widget')

        # EditText Field
        labelProjectName = QtGui.QLabel('Project Name:', self)
        labelProjectName.move(15, 10)

        self.etProjectName = QtGui.QLineEdit('', self)
        self.etProjectName.resize(self.etProjectName.sizeHint())
        self.etProjectName.move(90, 7)

        # Folder Browser
        lbBroswer = QtGui.QLabel('Directory:', self)
        lbBroswer.move(15, 40)

        self.etBrowser = QtGui.QLineEdit('', self)
        self.etBrowser.resize(210,20)
        self.etBrowser.move(90, 37)
        self.etBrowser.setEnabled(0)
        # self.etBrowser.isReadOnly = 0

        btnBrowse = QtGui.QPushButton('...', self)
        btnBrowse.setToolTip('Select directory for project location.')
        btnBrowse.resize(30,20)
        btnBrowse.move(305, 37)
        btnBrowse.clicked.connect(self.selectDirectory)

        # Button UI
        btn = QtGui.QPushButton('Create Folder', self)
        btn.setToolTip('This creates the folders.')
        btn.resize(btn.sizeHint())
        btn.move(5, 60)       
        btn.clicked.connect(self.generateFolders)

        self.resize(350, 150)
        self.center()

        self.setWindowTitle('Folder Utility')    
        self.show()

    def center(self):

        qr = self.frameGeometry()
        cp = QtGui.QDesktopWidget().availableGeometry().center()
        qr.moveCenter(cp)
        self.move(qr.topLeft())

    def selectDirectory(self):

        dialog = QtGui.QFileDialog()
        dialog.setFileMode(QtGui.QFileDialog.Directory)
        dialog.setOption(QtGui.QFileDialog.ShowDirsOnly)
        dialog.exec_()

        print 'select directory'

    def generateFolders(self):

        directory = "C:/Users/HP/Desktop/TRASH/Projects"
        projectName = self.etProjectName.text()
        folderNames = ['spam', 'ham', 'eggs']

        for f in folderNames:
            filePath = str(directory) +  "/" + str(projectName) + "/" + str(f)

            if not os.path.exists(filePath):
                os.makedirs(filePath)

        print 'Successfully Created Folders!'

def main():

    app = QtGui.QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

1 个答案:

答案 0 :(得分:11)

您应该使用QtGui.QFileDialog.getExistingDirectory

def selectDirectory(self):

    selected_directory = QtGui.QFileDialog.getExistingDirectory()

    # Use the selected directory...
    print 'selected_directory:', selected_directory