Skip to content
toylee blog · 컴퓨터, 프로그램 정보 공유

toylee blog · 컴퓨터, 프로그램 정보 공유

파이썬 pyqt6 qtableview 테이블 위젯 사용

toylee, 2023년 05월 21일

파이썬 PyQt6 QTableView 사용을 통해 테이블 형식으로 데이터를 표시하는 방법을 알아보려고 합니다. 마치 엑셀과 비슷한 위젯으로 실제로 내용을 작성하고, 지우고, 수정할 수 있습니다. 데이터를 다루는 프로그램 제작시 매우 유용합니다.

[목차]

  • 1. 파이썬 pyqt6 QTableView 생성
  • 2. 파이썬 pyqt6 QTableView 데이터 보기
  • 3. 파이썬 pyqt6 QTableView 데이터 수정
  • 4. 결론 및 의견

1. 파이썬 pyqt6 QTableView 생성

TableView를 생성하기 위해서는 QTableView 클래스를 사용합니다. 이 클래스는 PyQt6.QtWidgets 모듈에 포함되어 있습니다. 그럼 코드를 같이 살펴 보겠습니다.

1
2
3
4
from PyQt6.QtWidgets import QTableView
 
table_view = QTableView()
 
Colored by Color Scripter
cs
파이썬 pyqt6 qtableview 1

TableView를 생성한 후, 필요한 설정을 추가해 줄 수 있습니다. 예를 들어, TableView의 크기를 조절하거나, 각 열의 너비를 조절할 수 있습니다.

1
2
3
table_view.resize(600, 400) # 너비 600, 높이 400으로 설정
table_view.setColumnWidth(0, 200) # 첫 번째 열의 너비를 200으로 설정
 
Colored by Color Scripter
cs

2. 파이썬 pyqt6 QTableView 데이터 보기

생성한 TableView에 데이터를 보기 위해서는 모델 클래스를 만들어야 합니다. PyQt6에서는 QAbstractTableModel 클래스를 상속받아 모델 클래스를 만들 수 있습니다. 모델 클래스에서는 데이터를 저장하고, TableView에서 필요한 데이터를 제공하는 역할을 합니다.

모델 클래스에서는 다음과 같은 메서드를 구현해야 합니다.

  • rowCount(self, parent): 모델의 행(row) 수를 반환합니다.
  • columnCount(self, parent): 모델의 열(column) 수를 반환합니다.
  • data(self, index, role): 모델에서 특정 셀의 데이터를 반환합니다.

다음은 간단한 모델 클래스의 예시입니다:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
from PyQt6.QtCore import Qt, QAbstractTableModel
from PyQt6.QtWidgets import QApplication, QMainWindow, QTableView
import sys
 
 
class MyTableModel(QAbstractTableModel):
    def __init__(self, data):
        super().__init__()
        self._data = data
 
    def rowCount(self, parent):
        return len(self._data)
 
    def columnCount(self, parent):
        return len(self._data[0])
 
    def data(self, index, role):
        if role == Qt.ItemDataRole.DisplayRole:
            return str(self._data[index.row()][index.column()])
        return None
 
 
if __name__ == ‘__main__’:
    app = QApplication(sys.argv)
 
    data = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
    model = MyTableModel(data)
 
    table_view = QTableView()
    table_view.setModel(model)
 
    window = QMainWindow()
    window.setCentralWidget(table_view)
    window.show()
 
    # Start the application event loop
    sys.exit(app.exec())
 
Colored by Color Scripter
cs
파이썬 pyqt6 qtableview 보기

3. 파이썬 pyqt6 QTableView 데이터 수정

Edit Data 버튼 클릭시 수정 and 더블클릭시 데이터를 수정하는 예제를 만들어 보겠습니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
from PyQt6.QtCore import Qt, QAbstractTableModel
from PyQt6.QtWidgets import QApplication, QMainWindow, QTableView, QPushButton, QVBoxLayout, QWidget
import sys
 
 
class MyTableModel(QAbstractTableModel):
    def __init__(self, data):
        super().__init__()
        self._data = data
 
    def rowCount(self, parent):
        return len(self._data)
 
    def columnCount(self, parent):
        return len(self._data[0])
 
    def data(self, index, role):
        if role == Qt.ItemDataRole.DisplayRole:
            return str(self._data[index.row()][index.column()])
        return None
 
    def setData(self, index, value, role):
        if role == Qt.ItemDataRole.EditRole:
            self._data[index.row()][index.column()] = value
            self.dataChanged.emit(index, index)
            return True
        return False
 
    def flags(self, index):
        return super().flags(index) | Qt.ItemFlag.ItemIsEditable
 
 
class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
 
        self.data = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
        self.model = MyTableModel(self.data)
 
        self.table_view = QTableView()
        self.table_view.setModel(self.model)
 
        self.edit_button = QPushButton(“Edit Data”)
        self.edit_button.clicked.connect(self.editData)
 
        layout = QVBoxLayout()
        layout.addWidget(self.table_view)
        layout.addWidget(self.edit_button)
 
        widget = QWidget()
        widget.setLayout(layout)
        self.setCentralWidget(widget)
 
    def editData(self):
        # Activate edit mode on the selected cell
        index = self.table_view.currentIndex()
        if index.isValid():
            self.table_view.edit(index)
 
    def closeEvent(self, event):
        # Print the final data when closing the window
        print(“Final Data:”, self.data)
        event.accept()
 
 
if __name__ == ‘__main__’:
    app = QApplication(sys.argv)
 
    window = MainWindow()
    window.show()
 
    sys.exit(app.exec())
 
Colored by Color Scripter
cs
파이썬 pyqt6 qtableview edit

4. 결론 및 의견

TableView를 생성하고, 모델 클래스를 만들고, 모델을 TableView에 적용하는 방법을 살펴보았으며, TableView의 속성을 설정하여 사용자 경험을 개선하는 방법도 알아보았습니다. PyQt6를 사용하면 간단하게 GUI 프로그램을 개발할 수 있습니다. 특히, 테이블 형식의 데이터를 다루는 프로그램을 만들 경우 파이썬 pyqt6 qtableview 테이블 매우 유용한 도구입니다.

[관련글]

파이썬 QMessageBox, 다이얼로그, 파일창

PyQt6 QT Designer 사용자 지정 위젯

PyQt6 위젯 정리

파이썬 파이썬 pyqt6 qtableview

글 내비게이션

Previous post
Next post

Related Posts

파이썬

PyQt6 위젯 정리

2023년 05월 16일

PyQt6는 Python에서 GUI 프로그래밍을 위해 사용되는 강력한 라이브러리입니다. 이 라이브러리는 다양한 위젯을 제공하여 사용자가 직접 만든 윈도우, 대화 상자, 버튼 등을 만들 수 있게 해줍니다. pyqt6 위젯 알아봅시다.

Read More
파이썬

파이썬 변수(variable)와 상수(constant)

2023년 06월 29일

변수는 값이 언제든 변할 수 있는 data이며, 상수는 data 값이 변하지 않는다고 보시면 됩니다. 이 글에서는 파이썬 변수(variable)와 상수(constant)에 대해 설명하고 예시를 제공하겠습니다.

Read More
파이썬

파이썬 strip() 공백 문자 제거

2023년 06월 23일

파이썬은 다양한 문자열 조작 함수 중 strip()은 문자열에서 앞뒤에 있는 공백 문자를 제거할 수 있습니다. 이 글에서는 파이썬 strip() 함수의 다양한 기능과 활용법에 대해 실제 예제를 통해 알아보겠습니다.

Read More

답글 남기기 응답 취소

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다

최신 글

  • 드론 비행금지구역에 대해 알아볼게요
  • cpu 온도 측정 방법
  • 포토샵 단축키 모음 정리본
  • express vpn이란? 장점 및 단점
  • 안드로이드 버전 업그레이드 방법

최신 댓글

  1. 윈도우 단축키 모음 Best5의 ace
  2. http https 차이의 챗GPT 란? · Working for you

보관함

  • 2025년 7월
  • 2025년 6월
  • 2025년 5월
  • 2025년 4월
  • 2025년 3월
  • 2025년 2월
  • 2025년 1월
  • 2024년 12월
  • 2024년 11월
  • 2024년 8월
  • 2024년 6월
  • 2024년 5월
  • 2024년 3월
  • 2024년 2월
  • 2023년 11월
  • 2023년 9월
  • 2023년 8월
  • 2023년 7월
  • 2023년 6월
  • 2023년 5월
  • 2023년 4월
  • 2023년 3월
  • 2023년 2월

카테고리

  • flutter
  • html
  • linux
  • macbook
  • Pc Useful Tips
  • 미분류
  • 워드프레스
  • 자바(Java)
  • 파이썬
  • 프로그래밍
©2025 toylee blog · 컴퓨터, 프로그램 정보 공유 | WordPress Theme by SuperbThemes