Qtable에 정렬기능 추가

This commit is contained in:
Envy_PC 2024-04-19 21:57:02 +09:00
parent e5c16c42cd
commit 25e4f1643f
2 changed files with 90 additions and 44 deletions

View File

@ -48,6 +48,33 @@
<height>451</height>
</rect>
</property>
<property name="autoFillBackground">
<bool>true</bool>
</property>
<property name="verticalScrollBarPolicy">
<enum>Qt::ScrollBarAlwaysOn</enum>
</property>
<property name="horizontalScrollBarPolicy">
<enum>Qt::ScrollBarAlwaysOn</enum>
</property>
<property name="editTriggers">
<set>QAbstractItemView::AllEditTriggers</set>
</property>
<property name="alternatingRowColors">
<bool>true</bool>
</property>
<property name="horizontalScrollMode">
<enum>QAbstractItemView::ScrollPerItem</enum>
</property>
<property name="sortingEnabled">
<bool>true</bool>
</property>
<attribute name="horizontalHeaderCascadingSectionResizes">
<bool>true</bool>
</attribute>
<attribute name="verticalHeaderShowSortIndicator" stdset="0">
<bool>true</bool>
</attribute>
</widget>
<widget class="QLineEdit" name="overPrice">
<property name="geometry">
@ -337,6 +364,27 @@ font: 75 10pt &quot;Cafe24&quot;</string>
<height>231</height>
</rect>
</property>
<property name="font">
<font>
<family>굴림</family>
<pointsize>10</pointsize>
</font>
</property>
<property name="frameShape">
<enum>QFrame::Box</enum>
</property>
<property name="frameShadow">
<enum>QFrame::Raised</enum>
</property>
<property name="verticalScrollBarPolicy">
<enum>Qt::ScrollBarAlwaysOn</enum>
</property>
<property name="horizontalScrollBarPolicy">
<enum>Qt::ScrollBarAlwaysOn</enum>
</property>
<property name="autoFormatting">
<set>QTextEdit::AutoAll</set>
</property>
</widget>
</widget>
<widget class="QGroupBox" name="groupBox">

View File

@ -36,6 +36,10 @@ import logging
import ctypes
import atexit
from PyQt5.QtCore import QAbstractTableModel, Qt, QModelIndex
from PyQt5.QtGui import QColor, QFont
import pandas as pd
from PyQt5.QtCore import pyqtSignal, QObject
from PyQt5 import QtCore, QtGui, QtWidgets, uic
from PyQt5.QtCore import Qt, QUrl, pyqtSignal, QAbstractTableModel, QTimer, QObject, pyqtSlot, QEvent, QUrl, QTimer
@ -79,8 +83,11 @@ class CustomSpinBox(QSpinBox):
class PandasModel(QAbstractTableModel):
def __init__(self, data):
QAbstractTableModel.__init__(self)
super(PandasModel, self).__init__()
self._data = data
self.selected_cell = None # 선택된 셀 초기값 설정
self.sort_order = Qt.AscendingOrder
self.sort_column = 0
def rowCount(self, parent=None):
return self._data.shape[0]
@ -91,61 +98,51 @@ class PandasModel(QAbstractTableModel):
def data(self, index, role):
if not index.isValid():
return None
# 배경색 변경
if role == Qt.BackgroundColorRole:
# matching_url = self._data.iloc[index.row()]['MatchingUrl']
# matching_url = self._data['MatchingUrl'].iloc[index.row()]
matching_url = self._data.loc[index.row(), 'MatchingUrl']
if matching_url and matching_url.startswith('http'):
return QColor('lightgray')
if self.selected_cell == (index.row(), index.column()): # 선택된 셀
return QColor('yellow')
# 폰트 변경
if role == Qt.FontRole:
current_row = index.row()
current_keyword_id = self._data.iloc[current_row, 1]
# None 값 처리
if current_keyword_id is None:
current_keyword_id = ""
previous_keyword_id = ""
if current_row > 0:
previous_keyword_id = self._data.iloc[current_row - 1, 1]
if previous_keyword_id is None:
previous_keyword_id = ""
# 첫 번째 행이거나 이전 행보다 keyword_id가 큰 경우 폰트 스타일 변경
if current_row == 0 or current_keyword_id > previous_keyword_id:
font = QtGui.QFont()
font.setBold(True)
font.setUnderline(True)
return font
# 기타 데이터 처리
if role == Qt.DisplayRole:
return str(self._data.iloc[index.row(), index.column()])
elif role == Qt.BackgroundColorRole:
return self.background_color(index)
elif role == Qt.FontRole:
return self.font_style(index)
return None
def background_color(self, index):
matching_url = self._data.loc[index.row(), 'MatchingUrl']
if matching_url and matching_url.startswith('http'):
return QColor('lightgray')
if self.selected_cell == (index.row(), index.column()):
return QColor('yellow')
def font_style(self, index):
current_row = index.row()
current_keyword_id = self._data.iloc[current_row, 1]
previous_keyword_id = self._data.iloc[current_row - 1, 1] if current_row > 0 else ""
if current_row == 0 or current_keyword_id > previous_keyword_id:
font = QFont()
font.setBold(True)
font.setUnderline(True)
return font
def headerData(self, section, orientation, role):
if role == Qt.DisplayRole:
if orientation == Qt.Horizontal:
return self._data.columns[section]
else:
return str(self._data.index[section])
return None
def selected_cell(self, cell):
self.selected_cell = cell
self.layoutChanged.emit() # 뷰 업데이트
def update_selected_cell(self, cell):
self.selected_cell = cell
self.layoutChanged.emit() # 뷰 업데이트
self.layoutChanged.emit()
def sort(self, column, order):
try:
self.layoutAboutToBeChanged.emit()
self._data.sort_values(by=self._data.columns[column], ascending=(order == Qt.AscendingOrder), inplace=True)
self._data.reset_index(drop=True, inplace=True)
self.layoutChanged.emit()
except Exception as e:
print(f"Error sorting data: {e}")
class CustomWebEnginePage(QWebEnginePage):
def __init__(self, profile, parent=None, use_mobile=False):
@ -1352,6 +1349,7 @@ class Ui_Dialog(QtWidgets.QDialog):
# QTableView 설정
self.dbviewer1.setModel(model)
self.dbviewer1.setSortingEnabled(True) # 정렬 활성화
model.setHorizontalHeaderLabels(result.columns.values.tolist()) # 열 이름 설정
# 데이터베이스 연결 종료