Python

Python) 파일 목록 출력 - QLineEdit, QPushButton 이용

로픽 2022. 1. 11. 12:49
300x250

파일 목록 출력 - QLineEdit, QPushButton 이용

 

이전 포스팅에서 예제로 작성한 소스코드는 디렉토리 경로를 수정할 수 없이 고정 경로만 출력할 수 있었다.

이번 포스팅에선 QLineEdit와 QPushButton를 적용하여 원하는 디렉토리 리스트를 출력할 수 있도록 변경하였다.


* 소스코드

import sys, os
from PyQt5.QtWidgets import QApplication, QWidget, QTableWidget, QAbstractItemView, QHeaderView, QTableWidgetItem, QVBoxLayout, QLineEdit, QLabel, QPushButton, QMessageBox
from PyQt5.QtGui import QIcon

class MyApp(QWidget):

    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle('디렉토리 리스트 출력') #App Title
        self.setWindowIcon(QIcon('cloud.png')) #favicon

        # 위젯
        self.qline = QLineEdit(self)
        self.qtable = QTableWidget(self)
        qlabel = QLabel('출력할 경로를 입력하세요', self)
        qbtn = QPushButton('디렉토리 리스트 출력', self)
        
        # 클릭 이벤트
        qbtn.clicked.connect(self.btnRun_clicked)

        # BoxLayout 설정
        layout = QVBoxLayout()
        layout.addWidget(qlabel)
        layout.addWidget(self.qline)
        layout.addWidget(self.qtable)
        layout.addWidget(qbtn)

        # App 전체 레이어 설정
        self.setLayout(layout)
        self.setGeometry(300, 100, 600, 400) #App size
        self.show()

    # 클릭 이벤트 메소드
    def btnRun_clicked(self):
        dir_path = self.qline.text()
        if not dir_path:
            QMessageBox.about(self, '디렉토리 리스트 출력', '경로를 입력하세요')
        else:
            file_list = os.listdir(dir_path)
            file_list_count = file_list.__len__() #list 갯수

            self.qtable.setRowCount(file_list_count)
            self.qtable.setColumnCount(1)
            self.qtable.setEditTriggers(QAbstractItemView.NoEditTriggers)
            self.qtable.setHorizontalHeaderLabels(["Type", "Size", "Value"])
            self.qtable.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)

            for i in range(file_list_count):
                self.qtable.setItem(i, 0, QTableWidgetItem(file_list[i].format()))


if __name__ == '__main__':
   app = QApplication(sys.argv)
   ex = MyApp()
   sys.exit(app.exec_())

 


* GUI 화면

앱 실행 화면

 

디렉토리 리스트 출력 화면

 

디렉토리 경로 미입력시 Alert 창 출력

 

 

 

반응형