PyQt 5 QTableWidget.cellClicked信号不起作用

时间:2018-04-10 02:56:29

标签: python python-3.x pyqt pyqt5 qtablewidget

我正在尝试创建一个简单的文件应用程序(或文件浏览器应用程序),我正在使用QTableWidget来显示文件和目录。当用户单击目录时,我希望程序跳转到该目录。我已经使用了QTableWidget.cellClicked信号,它目前无法正常工作。

信号部分:

self.filesTable.connect(print)#self.updateUiCellClick)

为了调试目的,添加了print而不是self.updateUiCellClick。

代码(可能你不需要这个):     #!的/ usr / bin中/ python3

print('i Import Modules')
print(' | Import sys')
import sys
print(' | Import PyQt5.QtCore')
from PyQt5.QtCore import *
print(' | Import PyQt5.QtGui')
from PyQt5.QtGui import *
print(' | Import PyQt5.QtWidgets')
from PyQt5.QtWidgets import * # PyQt5 Support
print(' | Import os')
import os
print(' | Import subprocess.Popen') # For backward-compatibility
from subprocess import Popen, PIPE
print(' | Done')
print('i Define class Form')

class root(QMainWindow):

    def __init__(self, parent=None):
        '''self.__init__ - Initializes QMainWindow'''
        print('  self.__init__ - Initializes QMainWindow')
        super(root, self).__init__(parent)

        # Create Variables
        self.currentPath = '/'
        os.chdir(self.currentPath)
        self.currentItems = os.listdir()
        self.currentItemsLsProcess = Popen(['ls','-l'], stdout=PIPE, stderr=PIPE)
        self.currentItemsLsProcessResult = self.currentItemsLsProcess.communicate()
        if self.currentItemsLsProcessResult[1].decode('utf-8'):
            QMessageBox.warning(self,'Files - ls -l Error','ls -l responded with non-blank stderr.Error is shown here:<br><code>{}</code><br><hr><br>Error LsStderr (e-lsstderr)<br><hr><br>If you want to support the team, go to the <a href="https://github.com/">GitHub Repository</a>.'.format(self.currentItemsLsProcessResult[1].decode('utf-8')))
        self.currentItemsLs = self.currentItemsLsProcessResult[0].decode('utf-8').split('\n')[1:-1]

        # Create Table Widget
        self.filesTable = QTableWidget()

        # Init Table Widget
        self.filesTable.clear()
        self.filesTable.setSizeAdjustPolicy(QAbstractScrollArea.AdjustToContents)
        self.filesTable.setRowCount(len(self.currentItems))
        self.filesTable.setColumnCount(4)
        self.filesTable.setHorizontalHeaderLabels(['Name','TimeStamp','Type','ls -l'])
        # self.filesTable.setReadOnly(1)

        # Create & Add Items
        self.itemWidgets = [[],[],[],[]]
        for i in range(len(self.currentItems)):
            self.itemWidgets[0].append(QTableWidgetItem(self.currentItems[i]))
            self.filesTable.setItem(i,0,self.itemWidgets[0][-1])
            self.itemWidgets[3].append(QTableWidgetItem(self.currentItemsLs[i]))
            self.filesTable.setItem(i,3,self.itemWidgets[3][-1])

        # Init Widgets

        # Align Widgets to root
        self.setCentralWidget(self.filesTable)

        # Signals-and-Slots

        print('i Set self title')
        self.setWindowTitle('{}'.format(self.currentPath))

    def updateUi(self):
        '''self.updateUi - None'''
        os.chdir(self.currentPath)
        self.currentItems = os.listdir()
        self.currentItemsLsProcess = Popen(['ls','-l'], stdout=PIPE, stderr=PIPE)
        self.currentItemsLsProcessResult = self.currentItemsLsProcess.communicate()
        if self.currentItemsLsProcessResult[1].decode('utf-8'):
            QMessageBox.warning(self,'Files - ls -l Error','ls -l responded with non-blank stderr.Error is shown here:<br><code>{}</code><br><hr><br>Error LsStderr (e-lsstderr)<br><hr><br>If you want to support the team, go to the <a href="https://github.com/">GitHub Repository</a>.'.format(self.currentItemsLsProcessResult[1].decode('utf-8')))
        self.currentItemsLs = self.currentItemsLsProcessResult[0].decode('utf-8').split('\n')[1:-1]
        self.filesTable.clear()
        self.filesTable.setSizeAdjustPolicy(QtWidgets.QAbstractScrollArea.AdjustToContents)
        self.filesTable.setRowCount(len(self.currentItems))
        self.filesTable.setColumnCount(4)
        self.filesTable.setHorizontalHeaderLabels(['Name','TimeStamp','Type','ls -l'])
        self.itemWidgets = [[],[],[],[]]
        for i in range(len(self.currentItems)):
            self.itemWidgets[0].append(QTableWidgetItem(self.currentItems[i]))
            self.filesTable.setItem(i,0,self.itemWidgets[0][-1])
            self.filesTable..connect(print)#self.updateUiCellClick)
            self.itemWidgets[3].append(QTableWidgetItem(self.currentItemsLs[i]))
            self.filesTable.setItem(i,3,self.itemWidgets[3][-1])
        self.filesTable.resizeColumnsToContents()
        self.setWindowTitle('{}'.format(self.currentPath))

    def updateUiCellClick(self, row, column):
        '''self.updateUiCellClick - None'''
        print('self.updateUiCellClick - None')
        self.currentpath += self.itemWidgets[0][row].text+'/'
        self.updateUi()

print(' | Done')

if __name__ == '__main__':
    print('i Execute instance')
    app = QApplication(sys.argv)
    root = root()
    root.show()
    app.exec_()
    print(' | Done')

1 个答案:

答案 0 :(得分:1)

连接应如下

self.filesTable.cellClicked.connect(self.updateUiCellClick)
                ^^^^^^^^^^^
                   signal

除此之外,没有必要在每次填写表格时创建连接,在创建表格时就足够了。

如果您查看代码,您会看到许多部分正在重复,这是不必要的,我会大胆改进您的代码作为路径验证并减少代码。

import sys

import os
from subprocess import Popen, PIPE
from PyQt5.QtWidgets import *


class Root(QMainWindow):
    def __init__(self, parent=None):
        print('  self.__init__ - Initializes QMainWindow')
        QMainWindow.__init__(self, parent)
        # Create Table Widget
        self.filesTable = QTableWidget()
        self.filesTable.cellClicked.connect(self.updateUiCellClick)

        # Init Table Widget
        self.filesTable.clear()
        self.filesTable.setSizeAdjustPolicy(QTableWidget.AdjustToContents)
        self.filesTable.setColumnCount(4)
        self.filesTable.setHorizontalHeaderLabels(['Name', 'TimeStamp', 'Type', 'ls -l'])
        # Init Widgets

        self.setCentralWidget(self.filesTable)
        self.populate_table("/")

    def populate_table(self, path):
        # Verify that it is a directory.
        if not os.path.isdir(path):
            return

        os.chdir(path)
        current_items = os.listdir()
        currentItemsLsProcess = Popen(['ls', '-l'], stdout=PIPE, stderr=PIPE)

        currentItemsLsProcessResult = currentItemsLsProcess.communicate()
        if currentItemsLsProcessResult[1].decode('utf-8'):
            QMessageBox.warning(self, 'Files - ls -l Error',
                                'ls -l responded with non-blank stderr.Error is shown here:'
                                '<br><code>{}</code><br><hr><br>Error LsStderr (e-lsstderr)<br>'
                                '<hr><br>If you want to support the team, go to the '
                                '<a href="https://github.com/">GitHub Repository</a>.'.format(
                                    currentItemsLsProcessResult[1].decode('utf-8')))
            return

        self.filesTable.clear()
        currentItemsLs = currentItemsLsProcessResult[0].decode('utf-8').split('\n')[1:-1]
        self.filesTable.setRowCount(len(current_items))

        for i, values in enumerate(zip(current_items, currentItemsLs)):
            name, ls = values
            self.filesTable.setItem(i, 0, QTableWidgetItem(name))
            self.filesTable.setItem(i, 3, QTableWidgetItem(ls))

        self.setWindowTitle('{}'.format(path))

    def updateUiCellClick(self, row, _):
        path = os.path.join(os.getcwd(), self.filesTable.item(row, 0).text())
        self.populate_table(path)


if __name__ == '__main__':
    print('i Execute instance')
    app = QApplication(sys.argv)
    root = Root()
    root.show()
    status = app.exec_()
    print(' | Done')
    sys.exit(status)