facebook-tool/gui/tabs/settings/forms/setting_form.py

87 lines
2.8 KiB
Python

from PyQt6.QtWidgets import (
QDialog,
QVBoxLayout,
QLabel,
QLineEdit,
QComboBox,
QDialogButtonBox,
QMessageBox,
)
from PyQt6.QtCore import Qt
from PyQt6.QtGui import QIntValidator
class SettingForm(QDialog):
def __init__(self, key: str, value: str, type_: str = "text", parent=None):
super().__init__(parent)
self.setWindowTitle(f"Edit Setting '{key}'")
self.key = key
self.old_value = value
self.new_value = None
self.type_ = type_
self.layout = QVBoxLayout()
self.setLayout(self.layout)
# --- Label ---
lbl = QLabel(f"Update value for '{key}':")
self.layout.addWidget(lbl)
# --- Input Widget ---
self.input_widget = None
val_lower = (value or "").lower()
if self.type_ == "boolean" or val_lower in ("true", "false"):
self.input_widget = QComboBox()
self.input_widget.addItems(["true", "false"])
self.input_widget.setCurrentText(
val_lower if val_lower in ("true", "false") else "true"
)
else:
self.input_widget = QLineEdit()
self.input_widget.setText(value or "")
if self.type_ == "number":
self.input_widget.setValidator(QIntValidator())
self.layout.addWidget(self.input_widget)
# --- Buttons ---
buttons = QDialogButtonBox(
QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel
)
buttons.accepted.connect(self.on_accept)
buttons.rejected.connect(self.reject)
self.layout.addWidget(buttons)
# ----------------------------------------------------------------------
def on_accept(self):
"""Xử lý khi người dùng nhấn OK"""
if isinstance(self.input_widget, QLineEdit):
val = self.input_widget.text()
if self.type_ == "number" and not val.isdigit():
QMessageBox.warning(
self, "Invalid input", "Please enter a valid number."
)
return
elif isinstance(self.input_widget, QComboBox):
val = self.input_widget.currentText()
else:
val = self.old_value
if val == self.old_value:
self.reject()
return
self.new_value = val
self.accept()
# ----------------------------------------------------------------------
@staticmethod
def get_new_value(key: str, value: str, type_: str = "text", parent=None):
"""Hiển thị dialog và trả về giá trị mới"""
dialog = SettingForm(key, value, type_=type_, parent=parent)
result = dialog.exec() # ✅ PyQt6 dùng exec() thay vì exec_()
if result == QDialog.DialogCode.Accepted:
return dialog.new_value
return None