baidu_web/searchResultCard.py

150 lines
6.3 KiB
Python

from PySide6.QtWidgets import QWidget, QGridLayout, QLabel
from PySide6.QtGui import QPixmap
from PySide6.QtCore import Qt
import requests
# from translatepy import Translator
class SearchResultCard(QWidget):
def __init__(self, index=1, product_id=None, search_result_id=None, is_selected=False, cursor=None):
super().__init__()
self.index = index # 인덱스 속성 추가
self.product_id = product_id # 연결된 product의 ID
self.search_result_id = search_result_id # search_results 테이블의 고유 ID
# self.translator = Translator() # 클래스 변수로 Translator 생성
self.cursor = cursor # DB 커서
self.init_ui()
self.load_selection_from_db(is_selected) # 초기 선택 상태 반영
def init_ui(self):
self.setFixedSize(260, 400)
self.layout = QGridLayout(self)
# UI 요소 초기화
self.index_label = QLabel(str(self.index))
self.index_label.setAlignment(Qt.AlignCenter)
self.index_label.setStyleSheet("font-weight: bold; font-size: 16px;")
self.image_label = QLabel()
# self.image_label.setFixedSize(140, 120)
self.image_label.setFixedHeight(120)
self.name_label = QLabel("상품명:")
self.name_value = QLabel("")
self.name_value.setWordWrap(True)
# self.name_value.setFixedSize(120, 50)
self.name_value.setFixedHeight(80)
self.price_label = QLabel("가격:")
self.price_value = QLabel("")
self.source_label = QLabel("출처:")
self.source_value = QLabel("")
self.select_label = QLabel("미선택")
self.select_label.setAlignment(Qt.AlignCenter)
self.select_label.setStyleSheet("font-weight: bold; color: black;")
# 레이아웃 구성
self.layout.addWidget(self.index_label, 0, 0, 1, 2)
self.layout.addWidget(self.image_label, 1, 0, 1, 2)
self.layout.addWidget(self.name_label, 2, 0)
self.layout.addWidget(self.name_value, 2, 1)
self.layout.addWidget(self.price_label, 3, 0)
self.layout.addWidget(self.price_value, 3, 1)
self.layout.addWidget(self.source_label, 4, 0)
self.layout.addWidget(self.source_value, 4, 1)
self.layout.addWidget(self.select_label, 5, 0, 1, 2)
def reset(self):
"""카드의 데이터를 초기화합니다."""
self.name_value.setText("")
self.price_value.setText("")
self.source_value.setText("")
self.image_label.clear()
self.select_label.setText("미선택")
self.select_label.setStyleSheet("font-weight: bold; color: black;")
self.setStyleSheet("border: 1px solid grey;")
def set_data(self, name, price, source, saved_img_path, is_selected):
"""카드에 검색 결과 데이터를 설정하고 선택 상태를 적용합니다."""
# 상품명 번역
# translated_name = self.translate_name(name)
self.name_value.setText(name) # 번역된 이름 설정
self.price_value.setText(f"{price}")
self.source_value.setText(source)
self.load_selection_from_db(is_selected) # 초기 선택 상태 설정
pixmap = QPixmap(saved_img_path)
self.image_label.setPixmap(pixmap.scaled(self.image_label.size(), Qt.KeepAspectRatio))
# # 이미지 설정
# pixmap = QPixmap()
# img_data = self.download_image_data(img_url)
# if img_data:
# pixmap.loadFromData(img_data)
# self.image_label.setPixmap(pixmap.scaled(self.image_label.size(), Qt.KeepAspectRatio))
# else:
# self.image_label.clear()
def download_image_data(self, img_url):
"""이미지 URL에서 데이터를 다운로드합니다."""
try:
response = requests.get(img_url)
if response.status_code == 200:
return response.content
except Exception as e:
print(f"Image download error: {e}")
return None
def update_selection(self, selected):
"""사용자의 선택을 반영하여 UI와 데이터베이스를 업데이트합니다."""
if selected:
self.select_label.setText("선택")
self.select_label.setStyleSheet("font-weight: bold; color: red;")
self.setStyleSheet("border: 2px solid red;")
else:
self.select_label.setText("미선택")
self.select_label.setStyleSheet("font-weight: bold; color: black;")
self.setStyleSheet("border: 1px solid grey;")
# 데이터베이스에 선택 상태 업데이트
print(f"선택카드 DB 업데이트")
print(f"self.cursor = {self.cursor}, self.search_result_id = {self.search_result_id}")
# if self.cursor is not None and self.product_id is not None:
if self.cursor and self.search_result_id is not None:
try:
self.cursor.execute(
"UPDATE search_results SET is_selected = ? WHERE id = ?",
(1 if selected else 0, self.search_result_id)
)
self.cursor.connection.commit() # 변경 사항 커밋
print(f"Updated selection in DB for search_result_id: {self.search_result_id}, selected: {selected}")
except Exception as e:
print(f"Error updating selection in database: {e}", exc_info=True)
def load_selection_from_db(self, is_selected):
"""DB에서 가져온 선택 상태를 UI에만 반영합니다."""
if is_selected:
self.select_label.setText("선택")
self.select_label.setStyleSheet("font-weight: bold; color: red;")
self.setStyleSheet("border: 2px solid red;")
else:
self.select_label.setText("미선택")
self.select_label.setStyleSheet("font-weight: bold; color: black;")
self.setStyleSheet("border: 1px solid grey;")
# def translate_name(self, name):
# """상품명을 번역합니다."""
# try:
# result = self.translator.translate(name, "Korean") # 한국어로 번역
# if result:
# return result.result # 번역된 텍스트 반환
# else:
# return name # 번역 실패 시 원래 이름 반환
# except Exception as e:
# print(f"Translation error: {e}")
# return name