PyQt 5 QTableWidget.cellClicked 信号不工作

PyQt 5 QTableWidget.cellClicked Signal Not Working

我正在尝试制作一个简单的文件应用程序(或文件资源管理器应用程序),并且我正在使用 QTableWidget 来显示文件和目录。当用户单击目录时,我希望程序跳转到该目录。我已经使用了 QTableWidget.cellClicked 信号,但它目前不起作用。

信号部分:

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

为了调试目的添加了打印而不是 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')

连接应该如下

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

除此之外不需要每次填写table都创建连接,创建的时候就可以了

如果你看代码,很多地方都是重复的,这是没有必要的,我把大胆改进你的代码作为验证路径,减少代码。

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)