1

我正在构建这个应用程序,它默认到一个特定的位置,它将查看该文件夹中的所有文件夹以及这些文件夹中的文件数。尽管您没有配置文件,但它应该只打开您的 C 或主目录。这个想法是我会在那些我想要与之交互的文件的文件夹中打勾。我基本上在handleFolderChecked中有一个打印语句,让我知道我选择了正确的项目,并且它有效。

当我打开文件时出现问题- >从菜单栏打开然后点击弹出窗口上的选择文件夹按钮,无论是否选择,我最终都会在我的表格视图中显示一个新的显示,但是,如果我单击任何项​​目中的复选标记,打印语句将出现我打开“选择文件夹”窗口的项目数,这不是我想要的。

还有一些令人烦恼的事情,当我在“选择文件夹”窗口中点击取消时,程序将转储到主目录,有人知道我如何让它留在它所在的目录中吗?

from PyQt4 import QtCore, QtGui
from os import getcwd

from sys import platform
from sys import argv
from lxml import etree as ET


class Anaylzer(QtGui.QMainWindow):
    try:
        tree = ET.parse(''.join([getcwd(),'/config.xml']))
        if 'win' in platform:
            save_path = tree.find('SAVE').find('win').text
        if 'linux' in platform:
            save_path = tree.find('SAVE').find('linux').text
        del tree
    except IOError:
        if 'win' in platform:
            save_path = "C:/"
        if 'linux' in platform:
            save_path = "/home"        

    def __init__(self, parent=None):
        super(Anaylzer, self).__init__(parent)

        self.setWindowTitle("Anaylzer")
        self.resize(700,300)
        self.statusBar()

        self.pushWidgets()

        self.displayTableItems()

    '''Create objects'''
    def createFilesTable(self):        
        self.filesTable = QtGui.QTableWidget(0, 2)
        self.filesTable.setSelectionBehavior(QtGui.QAbstractItemView.SelectRows)
        self.filesTable.setHorizontalHeaderLabels(("Folder", "Files"))
        self.filesTable.horizontalHeader().setResizeMode(0, QtGui.QHeaderView.Stretch)
        self.filesTable.verticalHeader().hide()
        self.filesTable.setShowGrid(False)
    def createButton(self, text, member):
        button = QtGui.QPushButton(text)
        button.clicked.connect(member)
        return button

    '''Actions'''    
    def open(self):        
        directory = QtGui.QFileDialog.getExistingDirectory(self, "Select Folder",
                Anaylzer.save_path)
        Anaylzer.save_path = ''.join([str(directory),"\\"]) 
        self.displayTableItems()

    def displayTableItems(self):
        from os import listdir     
        self.filesTable.setRowCount(0)
        folders = listdir(Anaylzer.save_path)
        if folders:
            for fl in folders:
                folder_name_item = QtGui.QTableWidgetItem(fl)
                folder_name_item.setFlags(QtCore.Qt.ItemIsUserCheckable | QtCore.Qt.ItemIsEnabled)
                folder_name_item.setCheckState(QtCore.Qt.Unchecked)
                try:
                    folder_files_names = listdir(''.join([Anaylzer.save_path,fl]))
                    folder_files_count = QtGui.QTableWidgetItem(str(len(folder_files_names)))
                    folder_files_count.setFlags(QtCore.Qt.ItemIsEnabled)
                    folder_files_count.setTextAlignment(QtCore.Qt.AlignCenter)

                    row = self.filesTable.rowCount()
                    self.filesTable.insertRow(row)
                    self.filesTable.setItem(row, 0, folder_name_item)
                    self.filesTable.setItem(row, 1, folder_files_count)
                except WindowsError: pass
            self.filesTable.itemClicked.connect(self.handleFolderChecked)

    def handleFolderChecked(self, folder_name_item):
        if folder_name_item.checkState() == QtCore.Qt.Checked:
            print '{s} Checked'.format(s="".join([Anaylzer.save_path,str(folder_name_item.text())]))

    def createActions(self):
        self.openAct = QtGui.QAction("&Open...", self, shortcut=QtGui.QKeySequence.Open,
                statusTip="Open folder", triggered=self.open)
        self.exitAct = QtGui.QAction("E&xit", self, shortcut="Ctrl+Q",
                statusTip="Exit the application", triggered=self.close)

    def createMenus(self):
        self.fileMenu = self.menuBar().addMenu("&File")
        self.fileMenu.addAction(self.openAct)
        self.fileMenu.addAction(self.exitAct)

    '''Push widgets'''
    def pushWidgets(self):
        '''create'''
        self.createActions()
        self.createMenus()
        self.createFilesTable()
        '''put on window'''
        widget = QtGui.QWidget()
        self.setCentralWidget(widget)
        vbox = QtGui.QVBoxLayout()
        vbox.addStretch(1)
        vbox.addWidget(self.filesTable)
        widget.setLayout(vbox)

if __name__ == '__main__':
    app = QtGui.QApplication(argv)
    window = Anaylzer()
    window.show()
    app.exec_()
4

1 回答 1

1

好的,我想通了,显然负责调整QtGui.QTableWidgetItem的方法中也不能有 * .connect行,只需将self.filesTable.itemClicked.connect(self.handleFolderChecked)移出def displayTableItems(self)和将它放入一个只会被调用一次的方法中,但是在表构建之后,比如在def createFilesTable(self)的末尾或在该方法之外的任何地方,但在该方法之后,并且在程序只能运行的区域中它一次,然后它可以在没有上述错误的情况下工作。我将发布最终代码,以便任何人都可以看到简单的行移动如何解决我的问题。

from PyQt4 import QtCore, QtGui
from os import getcwd
from sys import platform
from sys import argv
from lxml import etree as ET


class Anaylzer(QtGui.QMainWindow):
    try:
        tree = ET.parse(''.join([getcwd(),'/config.xml']))
        if 'win' in platform:
            save_path = tree.find('SAVE').find('win').text
        if 'linux' in platform:
            save_path = tree.find('SAVE').find('linux').text
        del tree
    except IOError:
        if 'win' in platform:
            save_path = "C:/"
        if 'linux' in platform:
            save_path = "/home"        

    def __init__(self, parent=None):
        super(Anaylzer, self).__init__(parent)

        self.setWindowTitle("Anaylzer")
        self.resize(700,300)
        self.statusBar()

        self.pushWidgets()

        self.displayTableItems()

    '''Create objects'''
    def createFilesTable(self):        
        self.filesTable = QtGui.QTableWidget(0, 2)
        self.filesTable.setSelectionBehavior(QtGui.QAbstractItemView.SelectRows)
        self.filesTable.setHorizontalHeaderLabels(("Folder", "Files"))
        self.filesTable.horizontalHeader().setResizeMode(0, QtGui.QHeaderView.Stretch)
        self.filesTable.verticalHeader().hide()
        self.filesTable.setShowGrid(False)
        self.filesTable.itemClicked.connect(self.handleFolderChecked)
    def createButton(self, text, member):
        button = QtGui.QPushButton(text)
        button.clicked.connect(member)
        return button

    '''Actions'''    
    def open(self):        
        directory = QtGui.QFileDialog.getExistingDirectory(self, "Select Folder",
                Anaylzer.save_path)
        Anaylzer.save_path = ''.join([str(directory),"\\"])
        self.displayTableItems()

    def displayTableItems(self):
        from os import listdir     
        self.filesTable.setRowCount(0)
        folders = listdir(Anaylzer.save_path)
        if folders:
            for fl in folders:
                folder_name_item = QtGui.QTableWidgetItem(fl)
                folder_name_item.setFlags(QtCore.Qt.ItemIsUserCheckable | QtCore.Qt.ItemIsEnabled)
                folder_name_item.setCheckState(QtCore.Qt.Unchecked)
                try:
                    folder_files_names = listdir(''.join([Anaylzer.save_path,fl]))
                    folder_files_count = QtGui.QTableWidgetItem(str(len(folder_files_names)))
                    folder_files_count.setFlags(QtCore.Qt.ItemIsEnabled)
                    folder_files_count.setTextAlignment(QtCore.Qt.AlignCenter)

                    row = self.filesTable.rowCount()
                    self.filesTable.insertRow(row)
                    self.filesTable.setItem(row, 0, folder_name_item)
                    self.filesTable.setItem(row, 1, folder_files_count)
                except WindowsError: pass
            #self.filesTable.itemClicked.connect(self.handleFolderChecked)

    def handleFolderChecked(self, folder_name_item):
        if folder_name_item.checkState() == QtCore.Qt.Checked:
            print '{s} Checked'.format(s="".join([Anaylzer.save_path,str(folder_name_item.text())]))

    def createActions(self):
        self.openAct = QtGui.QAction("&Open...", self, shortcut=QtGui.QKeySequence.Open,
                statusTip="Open folder", triggered=self.open)
        self.exitAct = QtGui.QAction("E&xit", self, shortcut="Ctrl+Q",
                statusTip="Exit the application", triggered=self.close) 
    def createMenus(self):
        self.fileMenu = self.menuBar().addMenu("&File")
        self.fileMenu.addAction(self.openAct)
        self.fileMenu.addAction(self.exitAct)

    '''Push widgets'''
    def pushWidgets(self):
        '''create'''
        self.createActions()    
        self.createMenus()         
        self.createFilesTable()
        '''put on window'''
        widget = QtGui.QWidget()
        self.setCentralWidget(widget)
        vbox = QtGui.QVBoxLayout()
        vbox.addStretch(1)
        vbox.addWidget(self.filesTable)
        widget.setLayout(vbox)

if __name__ == '__main__':
    app = QtGui.QApplication(argv)
    window = Anaylzer()
    window.show()
    app.exec_()

我仍然不知道为什么 *QtGui.QFileDialog.getExistingDirectory(self, "Select Folder", Anaylzer.save_path)* 中的取消按钮将我转储到根目录,哦,好吧。

于 2012-11-19T11:10:28.307 回答