소연의_개발일지
article thumbnail

 

 

지금은 일일히 데이터를 추가해 줬지만 많은 양의 데이터가 있으면 따로 끌어와서 사용할 때 유용할 것 같다.

 

코드

 

import os
import sys

from PyQt5.QtWidgets import *
from PyQt5 import uic #모듈 가져오기
from PyQt5 import QtWidgets
from PyQt5.QtGui import QIcon


def resource_path(relative_path):
    base_path = getattr(sys, "_MEIPASS", os.path.dirname(os.path.abspath(__file__)))
    return os.path.join(base_path, relative_path)

form = resource_path('widget_blue.ui')
form_class = uic.loadUiType(form)[0]

class WindowClass(QMainWindow, form_class):
    def __init__(self):
        super( ).__init__( )
        self.setupUi(self)

        self.tableWidget.setColumnWidth(0,100) #첫번째 열 크기 고정
        self.tableWidget.setColumnWidth(1,50) #두번째 열 크기 고정
        self.tableWidget.setColumnWidth(2,250) #세번째 열 크기 조정
        self.tableWidget.setColumnWidth(3,200) #세번째 열 크기 조정
        self.loaddata()
        
        self.setWindowTitle("세븐틴 멤버")
        self.setWindowIcon(QIcon('seventeen.png'))
    def loaddata(self):
        """데이터 로드하기"""
        people=[
            {"Name":"에스쿱스","Age":"27","role":"총괄리더,래퍼","Team":"힙합팀"},
            {"Name":"정한","Age":"27","role":"서브보컬","Team":"보컬팀"},
            {"Name":"조슈아","Age":"27","role":"서브보컬","Team":"보컬팀"},
            {"Name":"준","Age":"26","role":"서브보컬,댄서","Team":"퍼포먼스팀"},
            {"Name":"호시","Age":"26","role":"퍼포먼스팀리더,메인댄서, 서브보컬","Team":"퍼포먼스팀"},
            {"Name":"원우","Age":"26","role":"래퍼","Team":"힙합팀"},
            {"Name":"우지","Age":"26","role":"보컬팀리더,리드보컬","Team":"보컬팀"},
            {"Name":"디에잇","Age":"25","role":"댄서,서브보컬","Team":"퍼포먼스팀"},
            {"Name":"민규","Age":"26","role":"래퍼","Team":"힙합팀"},
            {"Name":"도겸","Age":"26","role":"메인보컬","Team":"보컬팀"},
            {"Name":"승관","Age":"25","role":"메인보컬","Team":"보컬팀"},
            {"Name":"버논","Age":"25","role":"래퍼","Team":"힙합팀"},
            {"Name":"디노","Age":"24","role":"매인댄서,래퍼,서브보컬","Team":"퍼포먼스팀"},
        ]
        row = 0 #행값
        self.tableWidget.setRowCount(len(people)) #행의 갯수 지정. 열의 갯수 지정할 때는 setColumnCount 사용함
        for person in people:
            self.tableWidget.setItem(row, 0, QtWidgets.QTableWidgetItem(person["Name"]))
            self.tableWidget.setItem(row, 1, QtWidgets.QTableWidgetItem(person["Age"])) #만약 숫자로 썼다면 str로 변형해 줘야 함
            self.tableWidget.setItem(row, 2, QtWidgets.QTableWidgetItem(person["role"]))
            self.tableWidget.setItem(row, 3, QtWidgets.QTableWidgetItem(person["Team"]))
            row += 1

if __name__ == '__main__':
    app = QApplication(sys.argv)
    myWindow = WindowClass( )
    myWindow.show( )
    app.exec_( )
 

 

QTableWidget  가운데 정렬하기

        for person in people:
            name_item = QtWidgets.QTableWidgetItem(person['Name'])
            name_item.setTextAlignment(QtCore.Qt.AlignCenter)
            age_item = QtWidgets.QTableWidgetItem(person['Age'])
            age_item.setTextAlignment(QtCore.Qt.AlignCenter)
            role_item = QtWidgets.QTableWidgetItem(person['role'])
            role_item.setTextAlignment(QtCore.Qt.AlignCenter)
            team_item = QtWidgets.QTableWidgetItem(person['Team'])
            team_item.setTextAlignment(QtCore.Qt.AlignCenter)

            self.tableWidget.setItem(row, 0, QtWidgets.QTableWidgetItem(name_item))
            self.tableWidget.setItem(row, 1, QtWidgets.QTableWidgetItem(age_item))  # 만약 숫자로 썼다면 str로 변형해 줘야 함
            self.tableWidget.setItem(row, 2, QtWidgets.QTableWidgetItem(role_item))
            self.tableWidget.setItem(row, 3, QtWidgets.QTableWidgetItem(team_item))
            row += 1
 

QTableWidget  가운데 정렬하기 _ 2

        for i, person in enumerate(people):
            name_item = QtWidgets.QTableWidgetItem(person['Name'])
            name_item.setTextAlignment(QtCore.Qt.AlignCenter)
            self.tableWidget.setItem(i, 0, name_item)

            age_item = QtWidgets.QTableWidgetItem(str(person['Age']))  # 숫자일 경우 str로 변환 필요
            age_item.setTextAlignment(QtCore.Qt.AlignCenter)
            self.tableWidget.setItem(i, 1, age_item)

            role_item = QtWidgets.QTableWidgetItem(person['role'])
            role_item.setTextAlignment(QtCore.Qt.AlignCenter)
            self.tableWidget.setItem(i, 2, role_item)

            team_item = QtWidgets.QTableWidgetItem(person['Team'])
            team_item.setTextAlignment(QtCore.Qt.AlignCenter)
            self.tableWidget.setItem(i, 3, team_item)

참고링크: https://stackoverflow.com/questions/47168063/aligning-a-qtablewidgetitem-causes-item-to-be-none

 

Aligning a QTableWidgetItem causes item to be None

I have created a table in PyQt5 and populated it similar to how it's done in this post. I want to center align all the cells but when I try to align each cell my QTableWidgetItem becomes None.

stackoverflow.com

 

 

 

정렬한 것 적용한 코드

import os
import sys

from PyQt5.QtWidgets import *
from PyQt5 import uic #모듈 가져오기
from PyQt5 import QtWidgets
from PyQt5.QtGui import QIcon
from PyQt5 import QtCore


def resource_path(relative_path):
    base_path = getattr(sys, "_MEIPASS", os.path.dirname(os.path.abspath(__file__)))
    return os.path.join(base_path, relative_path)

form = resource_path('widget_blue.ui')
form_class = uic.loadUiType(form)[0]

class WindowClass(QMainWindow, form_class):
    def __init__(self):
        super( ).__init__( )
        self.setupUi(self)

        self.tableWidget.setColumnWidth(0,100) #첫번째 열 크기 고정
        self.tableWidget.setColumnWidth(1,70) #두번째 열 크기 고정
        self.tableWidget.setColumnWidth(2,300) #세번째 열 크기 조정
        self.tableWidget.setColumnWidth(3,220) #세번째 열 크기 조정
        self.loaddata()
        
    def loaddata(self):
        """데이터 로드하기"""
        people=[
            {"Name":"에스쿱스","Age":"27","role":"총괄리더,래퍼","Team":"힙합팀"},
            {"Name":"정한","Age":"27","role":"서브보컬","Team":"보컬팀"},
            {"Name":"조슈아","Age":"27","role":"서브보컬","Team":"보컬팀"},
            {"Name":"준","Age":"26","role":"서브보컬,댄서","Team":"퍼포먼스팀"},
            {"Name":"호시","Age":"26","role":"퍼포먼스팀리더,메인댄서, 서브보컬","Team":"퍼포먼스팀"},
            {"Name":"원우","Age":"26","role":"래퍼","Team":"힙합팀"},
            {"Name":"우지","Age":"26","role":"보컬팀리더,리드보컬","Team":"보컬팀"},
            {"Name":"디에잇","Age":"25","role":"댄서,서브보컬","Team":"퍼포먼스팀"},
            {"Name":"민규","Age":"26","role":"래퍼","Team":"힙합팀"},
            {"Name":"도겸","Age":"26","role":"메인보컬","Team":"보컬팀"},
            {"Name":"승관","Age":"25","role":"메인보컬","Team":"보컬팀"},
            {"Name":"버논","Age":"25","role":"래퍼","Team":"힙합팀"},
            {"Name":"디노","Age":"24","role":"매인댄서,래퍼,서브보컬","Team":"퍼포먼스팀"},
        ]

        self.tableWidget.setRowCount(len(people)) #행의 갯수 지정. 열의 갯수 지정할 때는 setColumnCount 사용함
        for i, person in enumerate(people):
            name_item = QtWidgets.QTableWidgetItem(person['Name'])
            name_item.setTextAlignment(QtCore.Qt.AlignCenter)
            self.tableWidget.setItem(i, 0, name_item)

            age_item = QtWidgets.QTableWidgetItem(str(person['Age']))  # 숫자일 경우 str로 변환 필요
            age_item.setTextAlignment(QtCore.Qt.AlignCenter)
            self.tableWidget.setItem(i, 1, age_item)

            role_item = QtWidgets.QTableWidgetItem(person['role'])
            role_item.setTextAlignment(QtCore.Qt.AlignCenter)
            self.tableWidget.setItem(i, 2, role_item)

            team_item = QtWidgets.QTableWidgetItem(person['Team'])
            team_item.setTextAlignment(QtCore.Qt.AlignCenter)
            self.tableWidget.setItem(i, 3, team_item)

        # self.tableWidget.setSortingEnabled(True)  # 정렬 기능 활성화
        # self.tableWidget.sortByColumn(1, QtCore.Qt.AscendingOrder)  # Age 열 기준 오름차순 정렬 (내림차순은 QtCore.Qt.DescendingOrder)

        # 여기에 시그널, 설정
    #여기에 함수 설정

if __name__ == '__main__':
    app = QApplication(sys.argv)
    myWindow = WindowClass( )
    myWindow.show( )
    app.exec_( )

 

QTableWidget  stylesheet 적용(qt designer에서)

QHeaderView selection 선택하여 스타일 적용하기

QHeaderView::section {
    background-color: red;
    color: white;
    font-size: 14px;
}
 

QHeaverView의 테두리 변경하기

QHeaderView {
    border: 2px solid red;
}
 
QHeaderView {
    border-left: 1px solid red;
    border-right: 1px solid red;
    border-top: 1px solid red;
    border-bottom: 2px double red;
}
 

적용한 스타일시트

QHeaderView {
    border: 2px solid rgb(175, 211, 226);
    font: 10pt "나눔스퀘어 네오 OTF Regular";
	
}
QHeaderView::section {background-color: rgb(246, 241, 241);}
background-color: background-color: rgb(246, 241, 241);
 
 
 
 
 

Color individual horizontal headers of QTableWidget in PyQt

I have a QTableWidget where I would like to color individual horizontal header items based on some criterion. What I have come up with so far: stylesheet = "::section{Background-color:rgb(190,1,...

stackoverflow.com

 

 

 

참고영상

참고영상: https://www.youtube.com/watch?v=xL2NdSubiNY&list=PLs3IFJPw3G9KhF7BeGOItwoKKLD8e3Dwu&index=3&ab_channel=CodeFirstwithHala

widget.zip
0.01MB

profile

소연의_개발일지

@ssoyxon

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!