id
int64 0
458k
| file_name
stringlengths 4
119
| file_path
stringlengths 14
227
| content
stringlengths 24
9.96M
| size
int64 24
9.96M
| language
stringclasses 1
value | extension
stringclasses 14
values | total_lines
int64 1
219k
| avg_line_length
float64 2.52
4.63M
| max_line_length
int64 5
9.91M
| alphanum_fraction
float64 0
1
| repo_name
stringlengths 7
101
| repo_stars
int64 100
139k
| repo_forks
int64 0
26.4k
| repo_open_issues
int64 0
2.27k
| repo_license
stringclasses 12
values | repo_extraction_date
stringclasses 433
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
2,288,400 | beep_example.py | zimolab_PyGUIAdapter/examples/beep_example.py | from pyguiadapter.adapter import GUIAdapter
from pyguiadapter.adapter import ubeep
def beep_example(beep: bool):
if beep:
ubeep.beep()
if __name__ == "__main__":
adapter = GUIAdapter()
adapter.add(beep_example)
adapter.run()
| 253 | Python | .py | 9 | 24 | 43 | 0.7 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,401 | uinput_custom_dialog_example.py | zimolab_PyGUIAdapter/examples/uinput_custom_dialog_example.py | import dataclasses
from datetime import date
from typing import Optional, Tuple
from qtpy.QtWidgets import QWidget, QLineEdit, QTextEdit, QDateEdit
from qtpy.uic import loadUi
from pyguiadapter.adapter import uinput, GUIAdapter
from pyguiadapter.adapter.uoutput import uprint
from pyguiadapter.extend_types import text_t
from pyguiadapter.utils import IconType
from pyguiadapter.utils.inputdialog import UniversalInputDialog
@dataclasses.dataclass
class UserInfo:
username: str
birthday: date
address: str
email: str
phone: str
description: str
class UserInfoDialog(UniversalInputDialog):
def __init__(
self,
parent: Optional[QWidget],
title: str = "",
icon: IconType = None,
size: Tuple[int, int] = (400, 300),
ok_button_text: str = "Ok",
cancel_button_text: Optional[str] = "Cancel",
initial_user_info: Optional[UserInfo] = None,
**kwargs
):
self._description_edit: Optional[QTextEdit] = None
self._phone_edit: Optional[QLineEdit] = None
self._email_edit: Optional[QLineEdit] = None
self._address_edit: Optional[QLineEdit] = None
self._birthday_edit: Optional[QDateEdit] = None
self._username_edit: Optional[QLineEdit] = None
self._initial_user_info: Optional[UserInfo] = initial_user_info
super().__init__(
parent,
title=title,
icon=icon,
size=size,
ok_button_text=ok_button_text,
cancel_button_text=cancel_button_text,
**kwargs
)
def get_result(self) -> UserInfo:
username = self._username_edit.text()
birthday = self._birthday_edit.date().toPyDate()
address = self._address_edit.text()
email = self._email_edit.text()
phone = self._phone_edit.text()
description = self._description_edit.toPlainText()
new_user_info = UserInfo(
username=username,
birthday=birthday,
address=address,
email=email,
phone=phone,
description=description,
)
return new_user_info
def create_main_widget(self) -> QWidget:
ui_file = "user_info_dialog_main_widget.ui"
# create widget from ui file
main_widget = loadUi(ui_file)
# obtain input widgets for UserInfo fields and set its initial values from initial_user_info
self._username_edit = main_widget.findChild(QLineEdit, "username_edit")
if self._initial_user_info:
self._username_edit.setText(self._initial_user_info.username)
self._birthday_edit = main_widget.findChild(QDateEdit, "birthday_edit")
if self._initial_user_info:
self._birthday_edit.setDate(self._initial_user_info.birthday)
self._address_edit = main_widget.findChild(QLineEdit, "address_edit")
if self._initial_user_info:
self._address_edit.setText(self._initial_user_info.address)
self._email_edit = main_widget.findChild(QLineEdit, "email_edit")
if self._initial_user_info:
self._email_edit.setText(self._initial_user_info.email)
self._phone_edit = main_widget.findChild(QLineEdit, "phone_edit")
if self._initial_user_info:
self._phone_edit.setText(self._initial_user_info.phone)
self._description_edit = main_widget.findChild(QTextEdit, "description_edit")
if self._initial_user_info:
self._description_edit.setText(self._initial_user_info.description)
return main_widget
def user_info_example(
initial_username: str = "",
initial_birthday: date = date(1990, 1, 1),
initial_address: str = "",
initial_email: str = "",
initial_phone: str = "",
initial_description: text_t = "",
):
user_info = uinput.get_custom_input(
UserInfoDialog,
title="Get User Info",
size=(350, 400),
ok_button_text="Confirm",
cancel_button_text="Dismiss",
initial_user_info=UserInfo(
username=initial_username,
birthday=initial_birthday,
address=initial_address,
email=initial_email,
phone=initial_phone,
description=initial_description,
),
)
uprint(user_info)
if __name__ == "__main__":
adapter = GUIAdapter()
adapter.add(user_info_example)
adapter.run()
| 4,446 | Python | .py | 114 | 30.842105 | 100 | 0.644944 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,402 | equation_solver_2.py | zimolab_PyGUIAdapter/examples/equation_solver_2.py | from typing import Optional
from pyguiadapter.adapter import GUIAdapter
from pyguiadapter.adapter.uoutput import uprint
from pyguiadapter.exceptions import ParameterError
from pyguiadapter.windows.fnexec import FnExecuteWindowConfig
def equation_solver_2(
a: float = 1.0, b: float = 0.0, c: float = 0.0
) -> Optional[tuple]:
"""A simple equation solver for equations like:
**ax^2 + bx + c = 0** (a, b, c ∈ **R** and a ≠ 0)
@param a: a ∈ R and a ≠ 0
@param b: b ∈ R
@param c: c ∈ R
@return:
"""
if a == 0:
raise ParameterError(parameter_name="a", message="a cannot be zero!")
uprint(f"Equation:")
uprint(f" {a}x² + {b}x + {c} = 0")
delta = b**2 - 4 * a * c
if delta < 0:
return None
x1 = (-b + delta**0.5) / (2 * a)
if delta == 0:
return x1, x1
x2 = (-b - delta**0.5) / (2 * a)
return x1, x2
if __name__ == "__main__":
window_config = FnExecuteWindowConfig(
title="Equation Solver",
icon="mdi6.function-variant",
execute_button_text="Solve",
size=(350, 550),
document_dock_visible=False,
output_dock_initial_size=(None, 100),
show_function_result=True,
function_result_message="roots: {}",
default_parameter_group_name="Equation Parameters",
)
adapter = GUIAdapter()
adapter.add(equation_solver_2, window_config=window_config)
adapter.run()
| 1,446 | Python | .py | 42 | 28.547619 | 77 | 0.616052 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,403 | udialog_text_messagebox_example.py | zimolab_PyGUIAdapter/examples/udialog_text_messagebox_example.py | import os.path
from typing import Literal
from pyguiadapter.adapter import GUIAdapter
from pyguiadapter.adapter import udialog
from pyguiadapter.exceptions import ParameterError
from pyguiadapter.extend_types import text_t, file_t
from pyguiadapter.utils import messagebox
def show_text_context_example(
content: text_t, text_format: Literal["markdown", "plaintext", "html"] = "markdown"
):
if content:
udialog.show_text_content(
title="Hello",
text_content=content,
text_format=text_format,
buttons=messagebox.DialogButtonYes | messagebox.DialogButtonNo,
size=(600, 400),
)
def show_text_file_example(
text_file: file_t,
text_format: Literal["markdown", "plaintext", "html"] = "markdown",
):
"""
Show text content of the file
@param text_file: the path of the text file
@param text_format: the format of the text file
@return:
@params
[text_file]
filters = "Text files(*.txt);;Markdown files(*.md);;HTML files(*.html);;All files(*.*)"
@end
"""
text_file = text_file.strip()
if not text_file:
raise ParameterError("text_file", "text_file is empty!")
if not os.path.isfile(text_file):
udialog.show_critical_messagebox(text="File not found", title="Error")
return
filename = os.path.basename(text_file)
if text_file:
udialog.show_text_file(
text_file=text_file,
text_format=text_format,
title=f"View - {filename}",
size=(600, 400),
)
if __name__ == "__main__":
adapter = GUIAdapter()
adapter.add(show_text_context_example)
adapter.add(show_text_file_example)
adapter.run()
| 1,737 | Python | .py | 51 | 27.843137 | 91 | 0.656325 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,404 | exclusive_actions_example.py | zimolab_PyGUIAdapter/examples/exclusive_actions_example.py | import qdarktheme
from pyguiadapter.action import Action
from pyguiadapter.adapter import GUIAdapter
from pyguiadapter.menu import Menu
from pyguiadapter.windows.fnselect import FnSelectWindow
def exclusive_action_example():
pass
def on_app_start(app):
qdarktheme.setup_theme("auto")
def on_action_auto(win: FnSelectWindow, action: Action, checked: bool):
if checked:
qdarktheme.setup_theme("auto")
def on_action_light(win: FnSelectWindow, action: Action, checked: bool):
if checked:
qdarktheme.setup_theme("light")
def on_action_dark(win: FnSelectWindow, action: Action, checked: bool):
if checked:
qdarktheme.setup_theme("dark")
action_auto = Action(
text="auto",
on_toggled=on_action_auto,
checkable=True,
checked=True,
)
action_light = Action(
text="light",
on_toggled=on_action_light,
checkable=True,
)
action_dark = Action(
text="dark",
on_toggled=on_action_dark,
checkable=True,
)
menu_theme = Menu(
title="Theme",
actions=[action_auto, action_light, action_dark],
exclusive=True,
)
if __name__ == "__main__":
adapter = GUIAdapter(on_app_start=on_app_start)
adapter.add(exclusive_action_example)
adapter.run(show_select_window=True, select_window_menus=[menu_theme])
| 1,299 | Python | .py | 43 | 26.302326 | 74 | 0.728006 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,405 | qtmodern_example.py | zimolab_PyGUIAdapter/examples/qtmodern_example.py | from datetime import datetime
from qtpy.QtWidgets import QApplication
from pyguiadapter.adapter import GUIAdapter
from pyguiadapter.extend_types import text_t
def app_style_example(
arg1: str, arg2: int, arg3: float, arg4: bool, arg5: text_t, arg6: datetime
):
"""
This example requires [qtmodern](https://github.com/gmarull/qtmodern).
Please install it before you run the example.
<br />
e.g. using `pip`:
> `pip install qtmodern`
@param arg1: arg1 description
@param arg2: arg2 description
@param arg3: arg3 description
@param arg4: arg4 description
@param arg5: arg5 description
@param arg6: arg6 description
@return:
@params
[arg6]
calendar_popup = true
@end
"""
pass
if __name__ == "__main__":
import qtmodern.styles
def on_app_start(app: QApplication):
# this will be called after the instantiation of QApplication.
print("app started")
qtmodern.styles.light(app)
adapter = GUIAdapter(on_app_start=on_app_start)
adapter.add(app_style_example)
adapter.run()
| 1,102 | Python | .py | 35 | 26.514286 | 79 | 0.696768 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,406 | docstring_as_document_example.py | zimolab_PyGUIAdapter/examples/docstring_as_document_example.py | from pyguiadapter.adapter import GUIAdapter
def function_1(arg1: int, arg2: str, arg3: bool):
"""
### Description
This is the document of the **function_1**. And by default this document will automatically
appear in the `document area`.
The format of the document is **Markdown** by default. The **plaintext** and **html** formats are also
supported.
---
### Arguments
This function needs 3 arguments:
- **arg1**: Balabala....
- **arg2**: Balabala....
- **arg3**: Balabala....
@param arg1:
@param arg2:
@param arg3:
@return:
"""
pass
if __name__ == "__main__":
adapter = GUIAdapter()
adapter.add(function_1)
adapter.run()
| 714 | Python | .py | 24 | 24.916667 | 106 | 0.6261 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,407 | progressbar_example.py | zimolab_PyGUIAdapter/examples/progressbar_example.py | import time
from pyguiadapter.adapter import GUIAdapter, udialog
from pyguiadapter.adapter import uprogress
from pyguiadapter.adapter.ucontext import is_function_cancelled
from pyguiadapter.adapter.uoutput import uprint
def progressbar_example(total: int = 100, delay: float = 0.5):
"""
example for **progressbar** and **cancellable function**
@param total: how many task will be processed
@param delay: how much time will be consumed per task
@return:
"""
uprogress.show_progressbar(0, total, message_visible=True)
cancelled = False
task_processed = 0
for i in range(total):
if is_function_cancelled():
uprint("Cancelled!")
cancelled = True
break
task_processed = i + 1
uprint(f"[Processed] {task_processed}")
uprogress.update_progress(
task_processed, info=f"[{task_processed}/{total}] please wait..."
)
time.sleep(delay)
if cancelled:
udialog.show_warning_messagebox(
f"{task_processed} task(s) processed!", title="Cancelled"
)
else:
udialog.show_info_messagebox(
f"{task_processed} task(s) processed!", title="Completed"
)
uprogress.hide_progressbar()
if __name__ == "__main__":
adapter = GUIAdapter()
adapter.add(progressbar_example, cancelable=True)
adapter.run()
| 1,392 | Python | .py | 39 | 29 | 77 | 0.66147 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,408 | html_file_document_example.py | zimolab_PyGUIAdapter/examples/html_file_document_example.py | from pyguiadapter import utils
from pyguiadapter.adapter import GUIAdapter
def function_3(arg1: int, arg2: str, arg3: bool):
"""
@param arg1:
@param arg2:
@param arg3:
@return:
"""
pass
if __name__ == "__main__":
adapter = GUIAdapter()
html_doc = utils.read_text_file("document.html")
adapter.add(function_3, document=html_doc, document_format="html")
adapter.run()
| 415 | Python | .py | 15 | 23.4 | 70 | 0.663291 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,409 | fn_execute_window_config_example.py | zimolab_PyGUIAdapter/examples/fn_execute_window_config_example.py | from pyguiadapter.adapter import GUIAdapter
from pyguiadapter.windows.fnexec import FnExecuteWindowConfig
def function_1(arg1: int, arg2: str, arg3: bool) -> None:
pass
def function_2(arg1: int, arg2: str, arg3: bool) -> None:
pass
if __name__ == "__main__":
adapter = GUIAdapter()
adapter.add(
function_1,
# set window config for function_1
window_config=FnExecuteWindowConfig(
title="Function 1", clear_checkbox_visible=True
),
)
adapter.add(
function_2,
# set window config for function_2
window_config=FnExecuteWindowConfig(
title="Function 2",
size=(400, 600),
clear_checkbox_visible=False,
clear_checkbox_checked=False,
document_dock_visible=False,
),
)
adapter.run()
| 848 | Python | .py | 27 | 23.962963 | 61 | 0.625767 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,410 | global_style_example_3.py | zimolab_PyGUIAdapter/examples/global_style_example_3.py | import os.path
from datetime import datetime
from qtpy.QtWidgets import QApplication
from pyguiadapter import utils
from pyguiadapter.adapter import GUIAdapter
from pyguiadapter.extend_types import text_t
def app_style_example(
arg1: str, arg2: int, arg3: float, arg4: bool, arg5: text_t, arg6: datetime
):
"""
This example shows how to apply a global stylesheet to the application.
In this example, [Ubuntu.qss](https://github.com/GTRONICK/QSS/blob/master/Ubuntu.qss)
will be used. This qss file is from GTRONICK's [QSS](https://github.com/GTRONICK/QSS) repo.
The QSS will be set in **on_app_start()** callback.
"""
pass
if __name__ == "__main__":
QSS_FILE = os.path.join(os.path.dirname(__file__), "Ubuntu.qss")
def on_app_start(app: QApplication):
assert isinstance(app, QApplication)
print("on_app_start")
qss = utils.read_text_file(QSS_FILE)
app.setStyleSheet(qss)
print("app style applied")
adapter = GUIAdapter(on_app_start=on_app_start)
adapter.add(app_style_example)
adapter.run()
| 1,092 | Python | .py | 27 | 35.666667 | 95 | 0.705213 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,411 | bool_example.py | zimolab_PyGUIAdapter/examples/widgets/bool_example.py | from pyguiadapter.adapter import GUIAdapter
from pyguiadapter.adapter.uoutput import uprint
from pyguiadapter.widgets import BoolBoxConfig
def bool_example(
bool_arg1: bool = False, bool_arg2: bool = True, bool_arg3: bool = False
):
"""
example for type **bool** and **BoolBox** widget
@param bool_arg1: this parameter will be configured in docstring
@param bool_arg2: this parameter will be configured with **adapter.run()** via a BoolBoxConfig object
@param bool_arg3: this parameter will be configured with **adapter.run()** via a dict
@return:
@params
[bool_arg1]
# this will override the default value defined in the function signature
default_value = true
true_text = "On"
false_text = "Off"
true_icon = "fa.toggle-on"
false_icon = "fa.toggle-off"
vertical = false
@end
"""
uprint(bool_arg1, bool_arg2, bool_arg3)
return bool_arg1, bool_arg2, bool_arg3
if __name__ == "__main__":
bool_arg2_conf = {
# this will override the default value defined in the function signature
"default_value": True,
"true_text": "Enable",
"false_text": "Disable",
"true_icon": "fa.toggle-on",
"false_icon": "fa.toggle-off",
"vertical": True,
}
bool_arg3_conf = BoolBoxConfig(
# this will override the default value defined in the function signature
default_value=True,
true_text="true",
false_text="false",
vertical=False,
)
adapter = GUIAdapter()
adapter.add(
bool_example,
widget_configs={"bool_arg2": bool_arg2_conf, "bool_arg3": bool_arg3_conf},
)
adapter.run()
| 1,684 | Python | .py | 48 | 29.229167 | 105 | 0.656423 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,412 | float_t_example.py | zimolab_PyGUIAdapter/examples/widgets/float_t_example.py | from pyguiadapter.adapter import GUIAdapter
from pyguiadapter.adapter.uoutput import uprint
from pyguiadapter.extend_types import float_t
from pyguiadapter.widgets import FloatLineEditConfig
def float_t_example(arg1: float_t, arg2: float_t, arg3: float_t = 100) -> float:
"""
This is an example for **float_t** type hint and **FloatLineEdit** widget.
@param arg1: description for arg1
@param arg2: description for arg2
@param arg3: description for arg3
@return:
@params
[arg1]
default_value = -100.0
min_value = -100.0
max_value = 100.0
[arg2]
default_value = 99999999.0
max_value = 99999999.0
empty_value = -1.0
decimals = 3
scientific_notation = true
@end
"""
uprint("arg1:", arg1)
uprint("arg2:", arg2)
uprint("arg3:", arg3)
return arg1 + arg2 + arg3
if __name__ == "__main__":
arg3_conf = FloatLineEditConfig(
default_value=-0.00005,
min_value=-100.0,
max_value=100.0,
empty_value=None,
decimals=5,
scientific_notation=True,
clear_button=True,
placeholder="Enter a float value",
)
adapter = GUIAdapter()
adapter.add(
float_t_example,
widget_configs={"arg3": arg3_conf},
)
adapter.run()
| 1,297 | Python | .py | 45 | 23.222222 | 80 | 0.646253 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,413 | literal_example.py | zimolab_PyGUIAdapter/examples/widgets/literal_example.py | from typing import Literal
from pyguiadapter.adapter import GUIAdapter
from pyguiadapter.adapter.uoutput import uprint
from pyguiadapter.widgets import ExclusiveChoiceBoxConfig
class MyObj(object):
def __init__(self, name: str):
self._name = name
def __str__(self):
return self._name
def __eq__(self, other):
if isinstance(other, MyObj):
return other._name == self._name
return False
def __hash__(self):
return hash(self._name)
my_objects = [MyObj("obj1"), MyObj("obj2"), MyObj("obj3")]
def literal_example(
arg1: Literal["option1", "option2", "option3"] = "option2",
arg2: Literal[1, 2, 3, 4, 5] = 3,
arg3: Literal["option1", "option2", 1, 2, True, False] = 1,
arg4: MyObj = my_objects[0],
):
"""
This is an example for **ExclusiveChoiceBox** widget and **Literal** type hint.
Args:
arg1: description of arg1
arg2: description of arg2
arg3: description of arg3
arg4: description of arg4
Returns:
None
@params
[arg3]
columns = 2
show_type_icon = false
@end
"""
uprint("arg1: ", arg1)
uprint("arg2: ", arg2)
uprint("arg3: ", arg3)
uprint(f"arg4: {arg4}({type(arg4)})")
if __name__ == "__main__":
arg4_conf = ExclusiveChoiceBoxConfig(
# this will override the default value defined in the function signature
default_value=my_objects[1],
show_type_icon=True,
choices=my_objects,
object_icon="ei.asl",
)
adapter = GUIAdapter()
adapter.add(literal_example, widget_configs={"arg4": arg4_conf})
adapter.run()
| 1,657 | Python | .py | 52 | 25.961538 | 83 | 0.628931 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,414 | dict_example.py | zimolab_PyGUIAdapter/examples/widgets/dict_example.py | from typing import Dict, Mapping, MutableMapping, TypedDict
from pyguiadapter.adapter import GUIAdapter
from pyguiadapter.adapter.uoutput import uprint
from pyguiadapter.widgets import DictEditConfig
class User(TypedDict):
name: str
age: int
address: str
email: str
def dict_example(
arg1: dict, arg2: Dict, arg3: MutableMapping, arg4: Mapping, arg5: User
):
"""
This is an example for **DictEdit** widget and **dict** types.
Args:
arg1: description of arg1
arg2: description of arg2
arg3: description of arg3
arg4: description of arg4
arg5: description of arg5
Returns:
None
@params
[arg1]
default_value = {a=1,b=2,c="3"}
[arg2]
default_value = {"key1"="value1", "key2"="value2"}
@end
"""
uprint("arg1: ", arg1)
uprint("arg2: ", arg2)
uprint("arg3: ", arg3)
uprint("arg4: ", arg4)
uprint("arg5: ", arg5)
if __name__ == "__main__":
arg1_conf = DictEditConfig(
default_value={"a": 1, "b": 2, "c": "3", "d": [1, 2, 3]},
)
arg3_conf = DictEditConfig(
default_value={"a": "A", "b": "B"},
)
arg4_conf = DictEditConfig(
default_value={"c": "C", "d": "D", "e": [1, 2, 3, 4]},
)
arg5_conf = DictEditConfig(
default_value=User(
name="John", age=30, address="123 Main St", email="[email protected]"
),
)
adapter = GUIAdapter()
adapter.add(
dict_example,
widget_configs={
"arg1": arg1_conf,
"arg3": arg3_conf,
"arg4": arg4_conf,
"arg5": arg5_conf,
},
)
adapter.run()
| 1,674 | Python | .py | 60 | 21.583333 | 80 | 0.575985 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,415 | plain_dict_t_example.py | zimolab_PyGUIAdapter/examples/widgets/plain_dict_t_example.py | from pyguiadapter.adapter import GUIAdapter
from pyguiadapter.adapter.uoutput import uprint
from pyguiadapter.widgets import PlainDictEditConfig
from pyguiadapter.extend_types import plain_dict_t
def plain_dict_t_example(arg1: plain_dict_t, arg2: plain_dict_t, arg3: plain_dict_t):
"""
This is an example for type **plain_dict_t** type hint and **PlainDictEdit** widget.
@param arg1: description for arg1
@param arg2: description for arg2
@param arg3: description for arg3
@params
[arg3]
default_value = {key1=1,key2="value",key3=true,key4=[1,2,3.0]}
@end
"""
uprint("arg1:", arg1, "type: ", type(arg1))
uprint("arg2:", arg2, "type: ", type(arg2))
uprint("arg3:", arg3, "type: ", type(arg3))
if __name__ == "__main__":
arg1_conf = PlainDictEditConfig(
default_value={
"key1": 1,
"key2": "value",
"key3": True,
"key4": [1, 2, 3.0],
"key5": None,
"key6": {"key7": 1},
}
)
arg2_conf = PlainDictEditConfig(
default_value={
"Content-Type": "application/json",
"Authorization": "Bearer token123",
},
key_header="Header",
value_header="Value",
vertical_header_visible=True,
)
adapter = GUIAdapter()
adapter.add(
plain_dict_t_example, widget_configs={"arg1": arg1_conf, "arg2": arg2_conf}
)
adapter.run()
| 1,448 | Python | .py | 43 | 26.837209 | 88 | 0.604435 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,416 | key_sequence_t_example.py | zimolab_PyGUIAdapter/examples/widgets/key_sequence_t_example.py | from pyguiadapter.adapter import GUIAdapter
from pyguiadapter.adapter.uoutput import uprint
from pyguiadapter.extend_types import key_sequence_t
from pyguiadapter.widgets import KeySequenceEditConfig, KeySequenceEdit
def key_sequence_t_example(
arg1: key_sequence_t,
arg2: key_sequence_t,
arg3: key_sequence_t,
):
"""
This is an example for type **key_sequence_t** type hint and **KeySequenceEdit** widget.
@param arg1: description for arg1
@param arg2: description for arg2
@param arg3: description for arg3
@params
[arg1]
default_value = "Ctrl+Shift+V"
@end
"""
uprint("arg1:", arg1)
uprint("arg2:", arg2)
uprint("arg3:", arg3)
if __name__ == "__main__":
arg2_conf = KeySequenceEditConfig(default_value="Ctrl+Alt+D")
arg3_conf = KeySequenceEditConfig(
default_value="Ctrl+Shift+T",
key_sequence_format=KeySequenceEdit.PortableText,
return_type="list",
)
adapter = GUIAdapter()
adapter.add(
key_sequence_t_example, widget_configs={"arg2": arg2_conf, "arg3": arg3_conf}
)
adapter.run()
| 1,118 | Python | .py | 34 | 28 | 92 | 0.693309 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,417 | float_example.py | zimolab_PyGUIAdapter/examples/widgets/float_example.py | from pyguiadapter.adapter import GUIAdapter
from pyguiadapter.adapter.uoutput import uprint
from pyguiadapter.widgets import FloatSpinBoxConfig
def float_example(float_arg1: float, float_arg2: float, float_arg3: float = 3.14):
"""
example for **float** and **FloatSpinBox**
@param float_arg1: this parameter is configured in docstring , see `@params ... @end` block below
@param float_arg2: this parameter is configured with `run()` via a FloatSpinBoxConfig object
@param float_arg3: this parameter is configured with `run()` via a dict instance
@return:
@params
[float_arg1]
default_value = 1.0
max_value = 100.0
step = 2.0
decimals = 3
prefix = "r: "
suffix = "%"
@end
"""
uprint("float_arg1", float_arg1)
uprint("float_arg2", float_arg2)
uprint("float_arg3", float_arg3)
return float_arg1 + float_arg2 + float_arg3
if __name__ == "__main__":
adapter = GUIAdapter()
float_arg2_config = FloatSpinBoxConfig(
default_value=-0.5, max_value=1.0, step=0.000005, decimals=5, prefix="R: "
)
adapter.add(
float_example,
widget_configs={
"float_arg2": float_arg2_config,
"float_arg3": {
# this will override the default_value in the function signature
"default_value": 1,
"max_value": 2.0,
"step": 0.00001,
"decimals": 5,
},
},
)
adapter.run()
| 1,498 | Python | .py | 43 | 27.744186 | 101 | 0.617993 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,418 | enum_example.py | zimolab_PyGUIAdapter/examples/widgets/enum_example.py | from enum import Enum
from pyguiadapter.adapter import GUIAdapter
from pyguiadapter.adapter.uoutput import uprint
from pyguiadapter.utils import qta_icon
from pyguiadapter.widgets import EnumSelectConfig
class Weekday(Enum):
MONDAY = 1
TUESDAY = 2
WEDNESDAY = 3
THURSDAY = 4
FRIDAY = 5
SATURDAY = 6
SUNDAY = 7
class Color(Enum):
RED = 1
GREEN = 2
BLUE = 3
def enums_example(day_enums: Weekday, color_enums: Color = Color.GREEN):
"""
This is an example for type **enum** and **EnumSelect** widget.
@param day_enums: Enums for week days
@param color_enums: Enums for RGB colors
@return:
@params
[day_enums]
default_value = "MONDAY"
icons = {"MONDAY"="mdi6.numeric-1-circle", "TUESDAY"="mdi6.numeric-2-circle"}
@end
"""
uprint(day_enums)
uprint(color_enums)
if __name__ == "__main__":
color_enums_conf = EnumSelectConfig(
# this will override the default value defined in the function signature
default_value=Color.BLUE,
icons={
# you can use the Enum value as the key to its icon
"RED": qta_icon("mdi.invert-colors", color="red"),
"GREEN": qta_icon("mdi.invert-colors", color="green"),
"BLUE": qta_icon("mdi.invert-colors", color="blue"),
# or you can use the Enum value itself as the key to its icon
# Color.RED: qta_icon("mdi.invert-colors", color="red"),
# Color.GREEN: qta_icon("mdi.invert-colors", color="green"),
# Color.BLUE: qta_icon("mdi.invert-colors", color="blue"),
},
icon_size=(24, 24),
)
adapter = GUIAdapter()
adapter.add(enums_example, widget_configs={"color_enums": color_enums_conf})
adapter.run()
| 1,776 | Python | .py | 50 | 29.32 | 81 | 0.64119 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,419 | string_list_t_example.py | zimolab_PyGUIAdapter/examples/widgets/string_list_t_example.py | from pyguiadapter.adapter import GUIAdapter
from pyguiadapter.adapter.uoutput import uprint
from pyguiadapter.widgets import StringListEditConfig
from pyguiadapter.extend_types import string_list_t
def string_list_t_example(
arg1: string_list_t,
arg2: string_list_t,
arg3: string_list_t,
):
"""
This is an example for type **string_list_t** type hint and **StringListEdit** widget.
@param arg1: description for arg1
@param arg2: description for arg2
@param arg3: description for arg3
@params
[arg1]
default_value = ["a", "b", "c", "d"]
add_file = true
add_dir = false
file_filters = "Python files(*.py);;Text files(*.txt)"
@end
"""
uprint("arg1:", arg1)
uprint("arg2:", arg2)
uprint("arg3:", arg3)
if __name__ == "__main__":
arg2_conf = StringListEditConfig(add_file=False, add_dir=True)
arg3_conf = StringListEditConfig(add_file=False, add_dir=False)
adapter = GUIAdapter()
adapter.add(
string_list_t_example, widget_configs={"arg2": arg2_conf, "arg3": arg3_conf}
)
adapter.run()
| 1,097 | Python | .py | 33 | 28.727273 | 90 | 0.678977 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,420 | int_dail_t_example.py | zimolab_PyGUIAdapter/examples/widgets/int_dail_t_example.py | from pyguiadapter.adapter import GUIAdapter
from pyguiadapter.adapter.uoutput import uprint
from pyguiadapter.extend_types import int_dial_t
from pyguiadapter.widgets import DialConfig
def int_dial_t_example(
arg1: int_dial_t, arg2: int_dial_t, arg3: int_dial_t = 100
) -> int:
"""
This is an example for **int_dial_t** type hint and **Dial** widget.
@param arg1: description for arg1
@param arg2: description for arg2
@param arg3: description for arg3
@return:
@params
[arg1]
default_value = -100
min_value = -100
max_value = 100
[arg2]
max_value = 999
single_step = 2
tracking = false
prefix = "count: "
inverted_controls = true
inverted_appearance = true
@end
"""
uprint("arg1:", arg1)
uprint("arg2:", arg2)
uprint("arg3:", arg3)
return arg1 + arg2 + arg3
if __name__ == "__main__":
arg3_conf = DialConfig(
default_value=-99,
min_value=-100,
max_value=100,
suffix=" mv",
)
adapter = GUIAdapter()
adapter.add(int_dial_t_example, widget_configs={"arg3": arg3_conf})
adapter.run()
| 1,144 | Python | .py | 41 | 22.926829 | 72 | 0.64652 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,421 | tuple_example.py | zimolab_PyGUIAdapter/examples/widgets/tuple_example.py | from typing import Tuple
from pyguiadapter.adapter import GUIAdapter
from pyguiadapter.adapter.uoutput import uprint
from pyguiadapter.widgets import TupleEditConfig
def tuple_example(arg1: tuple, arg2: Tuple, arg3: tuple):
"""
This is an example for **TupleEdit** and **tuple** types
Args:
arg1: describes of arg1
arg2: describes of arg2
arg3: describes of arg3
Returns:
None
"""
uprint("arg1: ", arg1)
uprint("arg2: ", arg2)
uprint("arg3: ", arg3)
if __name__ == "__main__":
arg1_conf = TupleEditConfig(
default_value=(1, 2, 3),
)
arg2_conf = {
"default_value": (1, 2, 3, [1, 2, 3, 4]),
}
arg3_conf = TupleEditConfig(
default_value=(1, 2, 3),
label="Arg3",
# set editor_height or editor_width to 0 will hide the inplace editor
editor_height=0,
editor_width=0,
)
adapter = GUIAdapter()
adapter.add(
tuple_example,
widget_configs={
"arg1": arg1_conf,
"arg2": arg2_conf,
"arg3": arg3_conf,
},
)
adapter.run()
| 1,135 | Python | .py | 41 | 21.146341 | 77 | 0.590616 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,422 | int_slider_t_example.py | zimolab_PyGUIAdapter/examples/widgets/int_slider_t_example.py | from pyguiadapter.adapter import GUIAdapter
from pyguiadapter.adapter.uoutput import uprint
from pyguiadapter.extend_types import int_slider_t
from pyguiadapter.widgets import SliderConfig
from pyguiadapter.widgets.extend.slider import TickPosition
def int_slider_t_example(
arg1: int_slider_t, arg2: int_slider_t, arg3: int_slider_t = 100
) -> int:
"""
This is an example for **int_slider_t** type hint and **Slider** widget.
@param arg1: description for arg1
@param arg2: description for arg2
@param arg3: description for arg3
@return:
@params
[arg1]
default_value = -100
min_value = -100
max_value = 100
[arg2]
max_value = 999
single_step = 2
tracking = false
prefix = "count: "
tick_interval = 10
inverted_controls = true
inverted_appearance = true
@end
"""
uprint("arg1:", arg1)
uprint("arg2:", arg2)
uprint("arg3:", arg3)
return arg1 + arg2 + arg3
if __name__ == "__main__":
arg3_conf = SliderConfig(
default_value=-99,
min_value=-100,
max_value=100,
tick_position=TickPosition.TicksAbove,
tick_interval=2,
single_step=1,
page_step=10,
suffix=" mv",
)
adapter = GUIAdapter()
adapter.add(
int_slider_t_example,
widget_configs={"arg3": arg3_conf},
)
adapter.run()
| 1,386 | Python | .py | 50 | 22.36 | 76 | 0.649321 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,423 | file_t_example.py | zimolab_PyGUIAdapter/examples/widgets/file_t_example.py | import os.path
from pyguiadapter.adapter import GUIAdapter
from pyguiadapter.adapter.uoutput import uprint
from pyguiadapter.widgets import FileSelectConfig
from pyguiadapter.extend_types import file_t
def file_t_example(arg1: file_t, arg2: file_t, arg3: file_t):
"""
This is an example for type **file_t** type hint and **FileSelect** widget.
@param arg1: description for arg1
@param arg2: description for arg2
@param arg3: description for arg3
@params
[arg3]
placeholder = "input save path here"
save_file = true
dialog_title = "Save File"
@end
"""
uprint("arg1:", arg1)
uprint("arg2:", arg2)
uprint("arg3:", arg3)
if __name__ == "__main__":
arg1_conf = FileSelectConfig(
placeholder="input file path here",
filters="Text files(*.txt);;All files(*.*)",
dialog_title="Open File",
)
arg2_conf = FileSelectConfig(
default_value=os.path.abspath(__file__),
start_dir=os.path.expanduser("~"),
clear_button=True,
)
adapter = GUIAdapter()
adapter.add(file_t_example, widget_configs={"arg1": arg1_conf, "arg2": arg2_conf})
adapter.run()
| 1,174 | Python | .py | 35 | 28.428571 | 86 | 0.665782 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,424 | time_example.py | zimolab_PyGUIAdapter/examples/widgets/time_example.py | from datetime import time
from pyguiadapter.adapter import GUIAdapter
from pyguiadapter.adapter.uoutput import uprint
from pyguiadapter.widgets import TimeEditConfig, TimeEdit
from pyguiadapter.widgets.basic.datetimeedit import TimeSpec
def time_example(arg1: time, arg2: time, arg3: time):
"""
This is an example for **TimeEdit** and **datetime.time** type.
Args:
arg1: description of arg1
arg2: description of arg2
arg3: description of arg3
Returns:
None
@params
[arg3]
label = "Argument 3"
display_format = "HH小时mm分ss秒"
@end
"""
uprint("arg1:", arg1)
uprint("arg2:", arg2)
uprint("arg3:", arg3)
if __name__ == "__main__":
arg1_conf = TimeEditConfig(
default_value=time(hour=12, minute=30),
max_time=time(hour=23, minute=59),
min_time=time(hour=0, minute=0),
time_spec=TimeSpec.UTC,
)
arg2_conf = TimeEditConfig(
default_value=time(hour=20, minute=30),
max_time=time(hour=23, minute=59),
min_time=time(hour=12, minute=0),
alignment=TimeEdit.AlignCenter,
)
adapter = GUIAdapter()
adapter.add(
time_example,
widget_configs={"arg1": arg1_conf, "arg2": arg2_conf},
)
adapter.run()
| 1,292 | Python | .py | 42 | 24.690476 | 67 | 0.652068 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,425 | text_t_example.py | zimolab_PyGUIAdapter/examples/widgets/text_t_example.py | from pyguiadapter.adapter import GUIAdapter
from pyguiadapter.adapter.uoutput import uprint
from pyguiadapter.extend_types import text_t
from pyguiadapter.widgets import TextEditConfig
def text_t_example(arg1: text_t, arg2: text_t, arg3: text_t = "foo") -> str:
"""
This is an example for **text_t** type hint and **TextEdit** widget.
@param arg1: description for arg1
@param arg2: description for arg2
@param arg3: description for arg3
@return:
@params
[arg1]
default_value = "Hello World"
[arg2]
default_value = "你好,世界!"
@end
"""
assert isinstance(arg1, str)
assert isinstance(arg2, str)
assert isinstance(arg3, str)
uprint("arg1:", arg1)
uprint("arg2:", arg2)
uprint("arg3:", arg3)
return "{};{};{}".format(arg1, arg2, arg3)
if __name__ == "__main__":
arg3_conf = TextEditConfig(
default_value="bar",
placeholder="Please input some text here!",
)
adapter = GUIAdapter()
adapter.add(
text_t_example,
widget_configs={"arg3": arg3_conf},
)
adapter.run()
| 1,112 | Python | .py | 36 | 25.5 | 76 | 0.654649 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,426 | py_literal_edit_example.py | zimolab_PyGUIAdapter/examples/widgets/py_literal_edit_example.py | from typing import Any, Union
from pyguiadapter.adapter import GUIAdapter
from pyguiadapter.adapter.uoutput import uprint
from pyguiadapter.widgets import PyLiteralEditConfig
def py_literal_example(arg1: Any, arg2: object, arg3: Union[int, str]):
"""
This is an example of **PyLiteralEdit** widget and **Any**, **object**, **Union** types
Args:
arg1: description of arg1
arg2: description of arg2
arg3: description of arg3
Returns:
None
"""
uprint("arg1: ", arg1, f", type={type(arg1)}")
uprint("arg2: ", arg2, f", type={type(arg2)}")
uprint("arg3: ", arg3, f", type={type(arg3)}")
if __name__ == "__main__":
# PyLiteralEdit support the PyLiteralType, which is a Union of:
# bool, int, float, bytes, str, list, tuple, dict, set and NoneType.
arg1_config = PyLiteralEditConfig(
default_value=[1, 2, 3, 4],
)
arg2_config = PyLiteralEditConfig(
default_value=("a", "b", "c", "d"),
)
arg3_config = PyLiteralEditConfig(
default_value={1, 2, 3},
)
adapter = GUIAdapter()
adapter.add(
py_literal_example,
widget_configs={
"arg1": arg1_config,
"arg2": arg2_config,
"arg3": arg3_config,
},
)
adapter.run()
| 1,301 | Python | .py | 39 | 27.128205 | 91 | 0.614833 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,427 | choices_t_example.py | zimolab_PyGUIAdapter/examples/widgets/choices_t_example.py | from pyguiadapter.adapter import GUIAdapter
from pyguiadapter.adapter.uoutput import uprint
from pyguiadapter.extend_types import choices_t
from pyguiadapter.widgets import MultiChoiceBoxConfig
class MyObject(object):
def __init__(self, name: str):
self.name = name
def __eq__(self, other):
if not isinstance(other, MyObject):
return False
return self.name == other.name
def __hash__(self):
return hash(self.name)
def __str__(self):
# this method is very important
# the return value will be displayed as the ChoiceBox's item
return self.name
def choices_t_example(arg1: choices_t, arg2: choices_t, arg3: choices_t):
"""
This is an example for type **choices_t** type hint and **MultiChoiceBox** widget.
@param arg1: description for arg1
@param arg2: description for arg2
@param arg3: description for arg3
@params
[arg1]
default_value = ["opt1", "opt2"]
choices = ["opt1", "opt2", "opt3", "opt4", "opt5"]
@end
"""
uprint("arg1:", arg1)
uprint("arg2:", arg2)
uprint("arg3:", arg3)
if __name__ == "__main__":
arg2_conf = MultiChoiceBoxConfig(
choices=[MyObject("foo"), MyObject("bar"), MyObject("baz")]
)
arg3_conf = MultiChoiceBoxConfig(
default_value=(1, 2, 3),
choices={
"Option 1": 1,
"Option 2": 2,
"Option 3": 3,
"Option 4": 4,
"Option 5": 5,
},
columns=2,
)
adapter = GUIAdapter()
adapter.add(
choices_t_example, widget_configs={"arg2": arg2_conf, "arg3": arg3_conf}
)
adapter.run()
| 1,679 | Python | .py | 52 | 25.692308 | 86 | 0.60953 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,428 | int_example.py | zimolab_PyGUIAdapter/examples/widgets/int_example.py | from pyguiadapter.adapter import GUIAdapter
from pyguiadapter.adapter.uoutput import uprint
from pyguiadapter.widgets import IntSpinBoxConfig
def int_example(arg1: int, arg2: int, arg3: int = 100) -> int:
"""
A simple example for **int** and **IntSpinBox**
@param arg1: description for arg1
@param arg2: description for arg2
@param arg3: description for arg3
@return:
@params
# parameter widget config for arg1
[arg1]
default_value = -100
min_value = -100
max_value = 100
# parameter widget config for arg2
[arg2]
default_value = 1000
max_value = 999
prefix = "$"
@end
"""
uprint("arg1:", arg1)
uprint("arg2:", arg2)
uprint("arg3:", arg3)
return arg1 + arg2 + arg3
if __name__ == "__main__":
adapter = GUIAdapter()
adapter.add(
int_example,
widget_configs={
# parameter config for arg3
"arg3": IntSpinBoxConfig(
default_value=100, min_value=0, max_value=1000, step=10, prefix="$"
)
},
)
adapter.run()
| 1,095 | Python | .py | 39 | 22.102564 | 83 | 0.620459 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,429 | files_t_example.py | zimolab_PyGUIAdapter/examples/widgets/files_t_example.py | import os.path
from pyguiadapter.adapter import GUIAdapter
from pyguiadapter.adapter.uoutput import uprint
from pyguiadapter.widgets import MultiFileSelectConfig
from pyguiadapter.extend_types import files_t
def files_t_example(arg1: files_t, arg2: files_t, arg3: files_t):
"""
This is an example for type **files_t** type hint and **MultiFileSelect** widget.
@param arg1: description for arg1
@param arg2: description for arg2
@param arg3: description for arg3
@params
[arg3]
placeholder = "select files"
@end
"""
uprint("arg1:", arg1)
uprint("arg2:", arg2)
uprint("arg3:", arg3)
if __name__ == "__main__":
arg1_conf = MultiFileSelectConfig(
default_value=("a", "b"),
placeholder="input files here",
filters="Text files(*.txt);;All files(*.*)",
dialog_title="Open Files",
)
arg2_conf = MultiFileSelectConfig(
default_value=[os.path.abspath(__file__)],
start_dir=os.path.expanduser("~"),
clear_button=True,
)
adapter = GUIAdapter()
adapter.add(files_t_example, widget_configs={"arg1": arg1_conf, "arg2": arg2_conf})
adapter.run()
| 1,174 | Python | .py | 34 | 29.294118 | 87 | 0.666961 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,430 | directory_t_example.py | zimolab_PyGUIAdapter/examples/widgets/directory_t_example.py | import os.path
from pyguiadapter.adapter import GUIAdapter
from pyguiadapter.adapter.uoutput import uprint
from pyguiadapter.extend_types import directory_t, dir_t
from pyguiadapter.widgets import DirSelectConfig
def directory_t_example(arg1: directory_t, arg2: directory_t, arg3: dir_t):
"""
This is an example for type **directory_t**(**dir_t**) type hint and **DirSelect** widget.
@param arg1: description for arg1
@param arg2: description for arg2
@param arg3: description for arg3
@params
[arg3]
placeholder = "select path"
dialog_title = "Select Dir"
@end
"""
uprint("arg1:", arg1)
uprint("arg2:", arg2)
uprint("arg3:", arg3)
if __name__ == "__main__":
arg1_conf = DirSelectConfig(
placeholder="select save path",
dialog_title="Select Save Path",
)
arg2_conf = DirSelectConfig(
default_value=os.path.dirname(os.path.abspath(__file__)),
start_dir=os.path.expanduser("~"),
clear_button=True,
)
adapter = GUIAdapter()
adapter.add(
directory_t_example, widget_configs={"arg1": arg1_conf, "arg2": arg2_conf}
)
adapter.run()
| 1,169 | Python | .py | 35 | 28.285714 | 94 | 0.672291 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,431 | color_t_example.py | zimolab_PyGUIAdapter/examples/widgets/color_t_example.py | from pyguiadapter.adapter import GUIAdapter
from pyguiadapter.adapter.uoutput import uprint
from pyguiadapter.extend_types import color_t
from pyguiadapter.widgets import ColorPickerConfig
def color_t_example(arg1: color_t, arg2: color_t, arg3: color_t = "red"):
"""
example for type **color_t** and **ColorPicker** widget
@param arg1: description for arg1
@param arg2: description for arg2
@param arg3: description for arg3
@params
[arg1]
default_value = [25, 100, 100]
alpha_channel = false
return_type = "tuple"
@end
"""
uprint("arg1:", arg1)
uprint("arg2:", arg2)
uprint("arg3:", arg3)
if __name__ == "__main__":
arg2_conf = ColorPickerConfig(default_value="#effeef", return_type="str")
arg3_conf = ColorPickerConfig(
default_value="#feeffe", display_color_name=False, return_type="tuple"
)
adapter = GUIAdapter()
adapter.add(
color_t_example,
widget_configs={
"arg2": arg2_conf,
"arg3": arg3_conf,
},
)
adapter.run()
| 1,072 | Python | .py | 34 | 26.117647 | 78 | 0.65407 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,432 | datetime_example.py | zimolab_PyGUIAdapter/examples/widgets/datetime_example.py | from datetime import datetime
from pyguiadapter.adapter import GUIAdapter
from pyguiadapter.adapter.uoutput import uprint
from pyguiadapter.widgets import DateTimeEditConfig, DateTimeEdit
def datetime_example(arg1: datetime, arg2: datetime, arg3: datetime):
"""
This an example for **DateTimeEdit** widget and **datetime** type.
Args:
arg1: description of arg1.
arg2: description of arg2.
arg3: description of arg3.
Returns:
None.
@params
[arg2]
label = "Argument 2"
display_format = "dd.MM.yyyy HH:mm:ss"
@end
"""
uprint("arg1", arg1)
uprint("arg2", arg2)
uprint("arg3", arg3)
if __name__ == "__main__":
arg1_conf = DateTimeEditConfig(
min_datetime=datetime(2023, 1, 1),
max_datetime=datetime(2023, 12, 31),
time_spec=DateTimeEdit.UTC,
)
arg3_conf = DateTimeEditConfig(
default_value=datetime(2023, 6, 1, 12, 59, 59),
min_datetime=datetime(2023, 1, 1),
max_datetime=datetime(2023, 12, 31),
alignment=DateTimeEdit.AlignCenter,
calendar_popup=False,
)
adapter = GUIAdapter()
adapter.add(
datetime_example,
widget_configs={
"arg1": arg1_conf,
"arg3": arg3_conf,
},
)
adapter.run()
| 1,316 | Python | .py | 44 | 23.522727 | 70 | 0.635788 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,433 | json_object_t_example.py | zimolab_PyGUIAdapter/examples/widgets/json_object_t_example.py | from pyguiadapter.adapter import GUIAdapter
from pyguiadapter.adapter.uoutput import uprint
from pyguiadapter.widgets import JsonEditConfig
from pyguiadapter.extend_types import json_obj_t
def json_obj_t_example(arg1: json_obj_t, arg2: json_obj_t, arg3: json_obj_t):
"""
This is an example for type **json_obj_t** type hint and **JsonEdit** widget.
@param arg1: description for arg1
@param arg2: description for arg2
@param arg3: description for arg3
@params
[arg3]
default_value = true
@end
"""
uprint("arg1:", arg1, "type: ", type(arg1))
uprint("arg2:", arg2, "type: ", type(arg2))
uprint("arg3:", arg3, "type: ", type(arg3))
if __name__ == "__main__":
arg1_conf = JsonEditConfig(default_value=[1, 2, 3, "a", "b", {"a": 1, "b": 2}])
arg2_conf = JsonEditConfig(
default_value={"a": 1, "b": 2},
# height=0 or width=0 will make the inplace editor hidden.
height=0,
width=0,
)
adapter = GUIAdapter()
adapter.add(
json_obj_t_example, widget_configs={"arg1": arg1_conf, "arg2": arg2_conf}
)
adapter.run()
| 1,129 | Python | .py | 31 | 31.290323 | 83 | 0.642202 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,434 | int_t_example.py | zimolab_PyGUIAdapter/examples/widgets/int_t_example.py | from pyguiadapter.adapter import GUIAdapter
from pyguiadapter.adapter.uoutput import uprint
from pyguiadapter.extend_types import int_t
from pyguiadapter.widgets import IntLineEditConfig
def int_t_example(arg1: int_t, arg2: int_t, arg3: int_t = 100) -> int:
"""
This is an example for **int_t** type hint and **IntLineEdit** widget.
@param arg1: description for arg1
@param arg2: description for arg2
@param arg3: description for arg3
@return:
@params
[arg1]
default_value = -100
min_value = -100
max_value = 100
[arg2]
max_value = 999
empty_value = -1
@end
"""
assert isinstance(arg1, int)
assert isinstance(arg2, int)
assert isinstance(arg3, int)
uprint("arg1:", arg1)
uprint("arg2:", arg2)
uprint("arg3:", arg3)
return arg1 + arg2 + arg3
if __name__ == "__main__":
arg3_conf = IntLineEditConfig(
default_value=-99,
min_value=-100,
max_value=100,
empty_value=None,
placeholder="Enter a number",
clear_button=True,
)
adapter = GUIAdapter()
adapter.add(
int_t_example,
widget_configs={"arg3": arg3_conf},
)
adapter.run()
| 1,211 | Python | .py | 43 | 22.744186 | 74 | 0.644214 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,435 | color_hex_t_example.py | zimolab_PyGUIAdapter/examples/widgets/color_hex_t_example.py | from pyguiadapter.adapter import GUIAdapter
from pyguiadapter.adapter.uoutput import uprint
from pyguiadapter.extend_types import color_hex_t
from pyguiadapter.widgets import ColorPickerConfig
def color_hex_t_example(
arg1: color_hex_t,
arg2: color_hex_t,
arg3: color_hex_t = "red",
):
"""
This is an example for type **color_hex_t** type hint and **ColorPicker** widget.
@param arg1: description for arg1
@param arg2: description for arg2
@param arg3: description for arg3
@params
[arg1]
default_value = "#aaffbb"
alpha_channel = false
@end
"""
uprint("arg1:", arg1)
uprint("arg2:", arg2)
uprint("arg3:", arg3)
if __name__ == "__main__":
arg2_conf = ColorPickerConfig(default_value="#effeedff", alpha_channel=True)
arg3_conf = ColorPickerConfig(display_color_name=False)
adapter = GUIAdapter()
adapter.add(
color_hex_t_example, widget_configs={"arg2": arg2_conf, "arg3": arg3_conf}
)
adapter.run()
| 1,005 | Python | .py | 31 | 28 | 85 | 0.68905 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,436 | choice_t_example.py | zimolab_PyGUIAdapter/examples/widgets/choice_t_example.py | from pyguiadapter.adapter import GUIAdapter
from pyguiadapter.adapter.uoutput import uprint
from pyguiadapter.extend_types import choice_t
from pyguiadapter.widgets import ChoiceBoxConfig
class MyObject(object):
def __init__(self, name: str):
self.name = name
def __eq__(self, other):
if not isinstance(other, MyObject):
return False
return self.name == other.name
def __hash__(self):
return hash(self.name)
def __str__(self):
# this method is very important
# the return value will be displayed as the ChoiceBox's item
return self.name
def choice_t_example(arg1: choice_t, arg2: choice_t, arg3: choice_t, arg4: choice_t):
"""
This is an example for type **choice_t** type hint and **ChoiceBox** widget.
@param arg1: description for arg1
@param arg2: description for arg2
@param arg3: description for arg3
@param arg4: description for arg4
@return:
@params
[arg1]
# choices can be a list of numbers
choices = {"A"=1, "B"=2, "C"=3}
@end
"""
uprint("arg1:", arg1, f", type: {type(arg1)}")
uprint("arg2:", arg2, f", type: {type(arg2)}")
uprint("arg3:", arg3, f", type: {type(arg3)}")
uprint("arg4:", arg4, f", type: {type(arg4)}")
if __name__ == "__main__":
arg2_conf = ChoiceBoxConfig(
default_value="opt2",
# choices can be a list of strings
choices=["opt1", "opt2", "opt3", "opt4"],
editable=True,
)
obj1 = MyObject("apple")
obj2 = MyObject("banana")
obj3 = MyObject("orange")
arg3_conf = ChoiceBoxConfig(
default_value=obj2,
# choices can be a list of objects which have implemented __eq__ and __hash__ methods
choices=[obj1, obj2, obj3],
)
arg4_conf = ChoiceBoxConfig(
# choices can be a list of numbers
choices={"A": 1, "B": 2, "C": 3},
editable=True,
add_user_input=False,
)
adapter = GUIAdapter()
adapter.add(
choice_t_example,
widget_configs={"arg2": arg2_conf, "arg3": arg3_conf, "arg4": arg4_conf},
)
adapter.run()
| 2,147 | Python | .py | 62 | 28.403226 | 93 | 0.618656 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,437 | date_example.py | zimolab_PyGUIAdapter/examples/widgets/date_example.py | from datetime import date
from pyguiadapter.adapter import GUIAdapter
from pyguiadapter.adapter.uoutput import uprint
from pyguiadapter.widgets import DateEditConfig, DateEdit
def date_example(arg1: date, arg2: date, arg3: date):
"""
This is an example for **DateEdit** and **date** type.
Args:
arg1: description of arg1
arg2: description of arg2
arg3: description of arg3
Returns:
None
@params
[arg2]
label = "Argument 2"
display_format = "yyyy-MM-dd"
@end
"""
uprint("arg1", arg1)
uprint("arg2", arg2)
uprint("arg3", arg3)
if __name__ == "__main__":
arg1_conf = DateEditConfig(
min_date=date(2023, 1, 1),
max_date=date(2023, 12, 31),
)
arg3_conf = DateEditConfig(
default_value=date(2023, 6, 1),
min_date=date(2023, 1, 1),
max_date=date(2023, 12, 31),
calendar_popup=True,
alignment=DateEdit.AlignCenter,
time_spec=DateEdit.UTC,
)
adapter = GUIAdapter()
adapter.add(
date_example,
widget_configs={"arg1": arg1_conf, "arg3": arg3_conf},
)
adapter.run()
| 1,158 | Python | .py | 41 | 22.268293 | 62 | 0.625789 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,438 | str_example.py | zimolab_PyGUIAdapter/examples/widgets/str_example.py | from pyguiadapter.adapter import GUIAdapter
from pyguiadapter.adapter.uoutput import uprint
from pyguiadapter.widgets import LineEditConfig, LineEdit
def str_example(
str_arg1: str = "arg1",
str_arg2: str = "arg2",
str_arg3: str = "arg3",
str_arg4: str = "arg4",
str_arg5: str = "arg5",
):
"""
example for type **str** and **LineEdit** widget
@param str_arg1: this parameter will be configured in docstring
@param str_arg2: this parameter will be configured in docstring
@param str_arg3: this parameter will be configured in docstring
@param str_arg4: this parameter will be configured with adapter.run() via a LineEditConfig object
@param str_arg5: this parameter will be configured with adapter.run() via a dict
@return:
@params
[str_arg1]
# override the default value of str_arg1 defined in the function signature
default_value = "123456"
clear_button = true
max_length = 5
frame = false
[str_arg2]
input_mask = "000.000.000.000;_"
[str_arg3]
default_value = ""
placeholder = "this is a placeholder text"
@end
"""
uprint("str_example")
uprint("str_arg1:", str_arg1)
uprint("str_arg2:", str_arg2)
uprint("str_arg3:", str_arg3)
uprint("str_arg4:", str_arg4)
uprint("str_arg5:", str_arg5)
return str_arg1 + str_arg2 + str_arg3 + str_arg4 + str_arg5
if __name__ == "__main__":
str_arg4_conf = LineEditConfig(
# override the default value of str_arg4 defined in the function signature
default_value="this is a readonly text",
readonly=False,
echo_mode=LineEdit.PasswordEchoOnEditMode,
)
str_arg5_conf = {
"validator": r"^[a-zA-Z0-9]+$",
"alignment": LineEdit.AlignCenter,
}
adapter = GUIAdapter()
adapter.add(
str_example,
widget_configs={
"str_arg4": str_arg4_conf,
"str_arg5": str_arg5_conf,
},
)
adapter.run()
| 1,989 | Python | .py | 59 | 28 | 101 | 0.651879 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,439 | set_example.py | zimolab_PyGUIAdapter/examples/widgets/set_example.py | from typing import Set, MutableSet
from pyguiadapter.adapter import GUIAdapter
from pyguiadapter.adapter.uoutput import uprint
from pyguiadapter.widgets import SetEditConfig
def set_example(arg1: set, arg2: Set, arg3: MutableSet):
"""
This is an example for **SetEdit** for **set** types.
Args:
arg1: description of arg1.
arg2: description of arg2.
arg3: description of arg3.
Returns:
None.
"""
uprint("arg1: ", arg1)
uprint("arg2: ", arg2)
uprint("arg3: ", arg3)
if __name__ == "__main__":
arg1_conf = SetEditConfig(
default_value={1, 2, 3},
)
arg2_conf = SetEditConfig(
default_value={"a", "b", 1, 2},
)
arg3_conf = {
"default_value": {1, 2, 3, (1, 2, 3, 4)},
}
adapter = GUIAdapter()
adapter.add(
set_example,
widget_configs={
"arg1": arg1_conf,
"arg2": arg2_conf,
"arg3": arg3_conf,
},
)
adapter.run()
| 1,001 | Python | .py | 37 | 20.783784 | 57 | 0.579937 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,440 | color_tuple_t_example.py | zimolab_PyGUIAdapter/examples/widgets/color_tuple_t_example.py | from pyguiadapter.adapter import GUIAdapter
from pyguiadapter.adapter.uoutput import uprint
from pyguiadapter.extend_types import color_tuple_t
from pyguiadapter.widgets import ColorPickerConfig
def color_tuple_t_example(
arg1: color_tuple_t,
arg2: color_tuple_t,
arg3: color_tuple_t = (125, 230, 156),
):
"""
This is an example for type **color_tuple_t** type hint and **ColorPicker** widget.
@param arg1: description for arg1
@param arg2: description for arg2
@param arg3: description for arg3
@params
[arg1]
default_value = [255,0, 126]
alpha_channel = false
@end
"""
uprint("arg1:", arg1)
uprint("arg2:", arg2)
uprint("arg3:", arg3)
if __name__ == "__main__":
arg2_conf = ColorPickerConfig(default_value=(25, 25, 25, 255), alpha_channel=True)
arg3_conf = ColorPickerConfig(display_color_name=False)
adapter = GUIAdapter()
adapter.add(
color_tuple_t_example, widget_configs={"arg2": arg2_conf, "arg3": arg3_conf}
)
adapter.run()
| 1,038 | Python | .py | 31 | 29.064516 | 87 | 0.688312 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,441 | list_example.py | zimolab_PyGUIAdapter/examples/widgets/list_example.py | from typing import List
from pyguiadapter.adapter import GUIAdapter
from pyguiadapter.adapter.uoutput import uprint
from pyguiadapter.widgets import ListEditConfig
def list_example(arg1: list, arg2: List, arg3: list):
"""
This is an example for **ListEdit** and list** types
Args:
arg1: description of arg1
arg2: description of arg2
arg3: description of arg3
Returns:
None
@params
[arg1]
default_value = [1,2,3,4]
[arg2]
default_value = ["a", "b", 3, "d"]
@end
"""
uprint("arg1: ", arg1)
uprint("arg2: ", arg2)
uprint("arg3: ", arg3)
if __name__ == "__main__":
arg3_conf = ListEditConfig(
default_value=[1, 2, 3, 4, ["a", "b", 3, "d"]],
# set editor_height or editor_width to 0 will hide the inplace editor
editor_height=0,
editor_width=0,
)
adapter = GUIAdapter()
adapter.add(
list_example,
widget_configs={"arg3": arg3_conf},
)
adapter.run()
| 1,013 | Python | .py | 36 | 22.444444 | 77 | 0.613636 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,442 | app.py | zimolab_PyGUIAdapter/examples/packaging/app.py | import os.path
from typing import Optional
from pyguiadapter.action import Action
from pyguiadapter.adapter import GUIAdapter
from pyguiadapter.exceptions import ParameterError
from pyguiadapter.menu import Menu
from pyguiadapter.utils import messagebox
from pyguiadapter.windows.fnexec import FnExecuteWindowConfig, FnExecuteWindow
def equation_solver(a: float, b: float, c: float) -> Optional[tuple]:
"""
Solving Equations: ax^2 + bx + c = 0 (a,b,c ∈ R, a ≠ 0)
@param a: a ∈ R, a ≠ 0
@param b: b ∈ R
@param c: c ∈ R
@return:
"""
if a == 0:
raise ParameterError(parameter_name="a", message="a cannot be zero!")
delta = b**2 - 4 * a * c
if delta < 0:
return None
x1 = (-b + delta**0.5) / (2 * a)
if delta == 0:
return x1, x1
x2 = (-b - delta**0.5) / (2 * a)
return x1, x2
if __name__ == "__main__":
ABOUT_FILEPATH = os.path.join(os.path.dirname(__file__), "about.html")
def on_action_about(window: FnExecuteWindow, action: Action):
messagebox.show_text_file(
window, text_file=ABOUT_FILEPATH, text_format="html", title="About"
)
action_about = Action(
text="About",
icon="mdi6.information-outline",
on_triggered=on_action_about,
)
menu_help = Menu(title="Help", actions=[action_about])
window_config = FnExecuteWindowConfig(
title="Equation Solver",
icon="mdi6.function-variant",
execute_button_text="Solve",
size=(350, 450),
document_dock_visible=False,
output_dock_visible=False,
clear_button_visible=False,
clear_checkbox_visible=False,
show_function_result=True,
function_result_message="real roots: {}",
default_parameter_group_name="Equation Parameters",
print_function_error=False,
print_function_result=False,
)
adapter = GUIAdapter()
adapter.add(equation_solver, window_config=window_config, window_menus=[menu_help])
adapter.run()
| 2,040 | Python | .py | 56 | 30.089286 | 87 | 0.648649 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,443 | snippet_1.py | zimolab_PyGUIAdapter/examples/snippets/snippet_1.py | from pyguiadapter.adapter import GUIAdapter
def f1(a: str, b: int, c: float):
pass
def f2(a=10, b=0.5, c="hello", e=True, f=(1, 2, 3)):
pass
def f3(a, b, c):
"""
这是一个示例函数.
Args:
a (int): 参数a的描述.
b (str): 参数b的描述.
c (list): 参数c的描述.
Returns:
bool: 函数返回的结果描述.
"""
pass
adapter = GUIAdapter()
adapter.add(f1)
adapter.add(f2)
adapter.add(f3)
adapter.run()
| 488 | Python | .py | 21 | 15.666667 | 52 | 0.585242 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,444 | snippet_5.py | zimolab_PyGUIAdapter/examples/snippets/snippet_5.py | from pyguiadapter.adapter import GUIAdapter
def foo(a: int = -100, b: int = 1 + 1):
"""
@param a: this is parameter a
@param b: this is parameter b
@return:
"""
adapter = GUIAdapter()
adapter.add(foo)
adapter.run()
| 239 | Python | .py | 10 | 20.5 | 43 | 0.657778 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,445 | snippet_3.py | zimolab_PyGUIAdapter/examples/snippets/snippet_3.py | from pyguiadapter.adapter import GUIAdapter
from pyguiadapter.widgets import IntSpinBoxConfig, FloatSpinBoxConfig, BoolBoxConfig
def foo(a, b, c):
pass
def bar(a, b, c):
"""
bar
@param a:
@param b:
@param c:
@return:
@params
[a]
widget_class = "IntSpinBox"
[b]
widget_class = "FloatSpinBox"
[c]
widget_class = "BoolBox"
@end
"""
pass
configs = {
"a": IntSpinBoxConfig(),
"b": FloatSpinBoxConfig(),
"c": BoolBoxConfig(),
}
adapter = GUIAdapter()
adapter.add(foo, widget_configs=configs)
adapter.add(bar)
adapter.run()
| 608 | Python | .py | 30 | 16.233333 | 84 | 0.656085 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,446 | snippet_2.py | zimolab_PyGUIAdapter/examples/snippets/snippet_2.py | from pyguiadapter.widgets import IntSpinBoxConfig, IntSpinBox
print("IntSpinBox.ConfigClass == ", IntSpinBox.ConfigClass)
print(
"IntSpinBoxConfig.target_widget_class() == ", IntSpinBoxConfig.target_widget_class()
)
| 221 | Python | .py | 5 | 42.2 | 88 | 0.804651 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,447 | snippet_4.py | zimolab_PyGUIAdapter/examples/snippets/snippet_4.py | from pyguiadapter.adapter import GUIAdapter
from pyguiadapter.widgets import (
IntSpinBoxConfig,
SliderConfig,
TextEditConfig,
)
def foo(a: int, b: int, c: str = "hello world!"):
pass
def foo2(a: int, b: int, c: str = "hello world!"):
pass
foo_configs = {
"a": IntSpinBoxConfig(
default_value=1,
min_value=0,
max_value=10,
step=1,
label="a",
description="parameter a",
),
"b": SliderConfig(
default_value=50,
min_value=0,
max_value=100,
label="b",
description="parameter b",
),
"c": TextEditConfig(
default_value="Hello PyGUIAdapter!",
label="c",
description="parameter c",
),
}
foo2_configs = {
"a": {
"default_value": 1,
"min_value": 0,
"max_value": 10,
"step": 1,
"label": "a",
"description": "parameter a",
},
"b": {
"default_value": 50,
"min_value": 0,
"max_value": 100,
"label": "b",
"description": "parameter b",
},
"c": {
"default_value": "Hello PyGUIAdapter!",
"label": "c",
"description": "parameter c",
},
}
adapter = GUIAdapter()
adapter.add(foo, widget_configs=foo_configs)
adapter.add(foo2, widget_configs=foo2_configs)
adapter.run()
| 1,349 | Python | .py | 58 | 17.068966 | 50 | 0.551482 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,448 | snippet_6.py | zimolab_PyGUIAdapter/examples/snippets/snippet_6.py | from pyguiadapter.adapter import GUIAdapter
def foo(a: int, b: int, c: str = "hello world!"):
"""
@params
[a]
widget_class="IntSpinBox"
default_value=1
min_value=0
max_value=10
step=1
label="a"
description="parameter a"
[b]
widget_class="Slider"
default_value=50
min_value=0
max_value=100
label="b"
description="parameter b"
[c]
widget_class="TextEdit"
default_value="Hello PyGUIAdapter!"
label="c"
description="parameter c"
@end
"""
def foo2(a: int, b: int, c: str = "hello world!"):
"""
@params
[a]
default_value=1
min_value=0
max_value=10
step=1
label="a"
description="parameter a"
[b]
default_value=50
min_value=0
max_value=100
label="b"
description="parameter b"
[c]
default_value="Hello PyGUIAdapter!"
label="c"
description="parameter c"
@end
"""
adapter = GUIAdapter()
adapter.add(foo)
adapter.add(foo2)
adapter.run()
| 1,015 | Python | .py | 52 | 14.865385 | 50 | 0.622246 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,449 | pyguiadapter.widgets.pyliteraledit.md | zimolab_PyGUIAdapter/docs/apis/pyguiadapter.widgets.pyliteraledit.md | ## 控件配置类
::: pyguiadapter.widgets.PyLiteralEditConfig
options:
heading_level: 3
show_root_full_path: false
show_source: true
::: pyguiadapter.widgets.StandaloneCodeEditorConfig
options:
heading_level: 3
show_root_full_path: false
show_source: true
## 控件类
::: pyguiadapter.widgets.PyLiteralEdit
options:
heading_level: 3
show_root_full_path: false
show_source: false
## 对应参数数据类型
- `object`
- `typing.Any`
- `Union[str, int, float, bool, bytes, list, tuple, dict, set, None]` | 599 | Python | .py | 21 | 21.571429 | 69 | 0.664804 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,450 | textbrowser.py | zimolab_PyGUIAdapter/pyguiadapter/textbrowser.py | """
@Time : 2024.10.28
@File : textbrowser.py
@Author : zimolab
@Project : PyGUIAdapter
@Desc : 实现了通用文本浏览器控件及其配置类。
"""
import dataclasses
import webbrowser
from typing import Optional, Sequence, Union
from urllib.parse import unquote
from qtpy.QtCore import QUrl
from qtpy.QtGui import QTextOption, QColor, QPalette, QTextCursor
from qtpy.QtWidgets import QTextBrowser, QWidget
from .constants.color import COLOR_BASE_BACKGROUND, COLOR_BASE_TEXT
from .constants.font import FONT_LARGE
LineWrapMode = QTextBrowser.LineWrapMode
NoLineWrap = QTextBrowser.NoWrap
WidgetWidth = QTextBrowser.WidgetWidth
FixedPixelWidth = QTextBrowser.FixedPixelWidth
FixedColumnWidth = QTextBrowser.FixedColumnWidth
WordWrapMode = QTextOption.WrapMode
NoWrap = QTextOption.NoWrap
WordWrap = QTextOption.WordWrap
ManualWrap = QTextOption.ManualWrap
WrapAnywhere = QTextOption.WrapAnywhere
WrapAtWordBoundaryOrAnywhere = QTextOption.WrapAtWordBoundaryOrAnywhere
@dataclasses.dataclass
class TextBrowserConfig(object):
"""文本浏览器的配置类。"""
text_color: str = COLOR_BASE_TEXT
"""文本颜色。"""
font_family: Union[Sequence[str], str] = None
"文本的字体系列。"
font_size: Optional[int] = FONT_LARGE
"""文本的字体大小(px)。"""
background_color: str = COLOR_BASE_BACKGROUND
"""背景颜色。"""
line_wrap_mode: LineWrapMode = LineWrapMode.NoWrap
"""换行模式。"""
line_wrap_width: int = 88
"""换行宽度。"""
word_wrap_mode: WordWrapMode = WordWrapMode.WordWrap
"""“单词换行模式"""
open_external_links: bool = True
"""是否允许打开外部链接。"""
stylesheet: str = ""
"""样式表(QSS格式)。"""
class TextBrowser(QTextBrowser):
def __init__(self, parent: Optional[QWidget], config: Optional[TextBrowserConfig]):
self._config: TextBrowserConfig = config or TextBrowserConfig()
super().__init__(parent)
self._apply_config()
self.anchorClicked.connect(self.on_url_clicked)
def move_cursor_to_end(self):
cursor = self.textCursor()
cursor.clearSelection()
cursor.movePosition(QTextCursor.End)
self.setTextCursor(cursor)
def append_output(self, content: str, html: bool = False, html_tag: str = "div"):
self.move_cursor_to_end()
if content and not html:
self.insertPlainText(content)
return
if content:
self.insertHtml(f"<{html_tag}>" + content + f"</{html_tag}>")
self.insertHtml("<br />")
self.ensureCursorVisible()
def _apply_config(self):
palette = self.palette()
if self._config.background_color:
palette.setColor(QPalette.Base, QColor(self._config.background_color))
if self._config.text_color:
palette.setColor(QPalette.Text, QColor(self._config.text_color))
self.setPalette(palette)
font = self.font()
if self._config.font_family:
if isinstance(self._config.font_family, str):
font.setFamily(self._config.font_family)
else:
font.setFamilies(self._config.font_family)
if self._config.font_size:
font.setPixelSize(self._config.font_size)
self.setFont(font)
self.setLineWrapMode(self._config.line_wrap_mode)
if self._config.line_wrap_mode in (
LineWrapMode.FixedPixelWidth,
LineWrapMode.WidgetWidth,
):
assert self._config.line_wrap_width > 0
self.setLineWrapColumnOrWidth(self._config.line_wrap_width)
self.setWordWrapMode(self._config.word_wrap_mode)
self.setOpenLinks(False)
self.setOpenExternalLinks(self._config.open_external_links)
if self._config.stylesheet:
self.setStyleSheet(self._config.stylesheet)
def on_url_clicked(self, url: QUrl):
if not url or not url.isValid() or url.isEmpty():
return
if url.isRelative():
self.doSetSource(url)
return
if self._config.open_external_links:
url_ = unquote(url.toString())
webbrowser.open(url_)
| 4,251 | Python | .py | 105 | 31.809524 | 87 | 0.679807 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,451 | window.py | zimolab_PyGUIAdapter/pyguiadapter/window.py | """
@Time : 2024.10.20
@File : window.py
@Author : zimolab
@Project : PyGUIAdapter
@Desc : 定义了窗口基类,实现了窗口基本的外观和逻辑,并且实现了一些公共的接口方法。
"""
import dataclasses
from abc import abstractmethod
from concurrent.futures import Future
from typing import Tuple, Dict, List, Optional, Union, Sequence, Callable
from qtpy.QtCore import QSize, Qt, Signal
from qtpy.QtGui import QAction, QIcon, QActionGroup, QClipboard
from qtpy.QtWidgets import QMainWindow, QWidget, QToolBar, QMenu, QApplication
from .action import Action, Separator
from .constants.clipboard import (
CLIPBOARD_OWNS_CLIPBOARD,
CLIPBOARD_SET_TEXT,
CLIPBOARD_GET_TEXT,
CLIPBOARD_OWNS_SELECTION,
CLIPBOARD_SUPPORTS_SELECTION,
CLIPBOARD_GET_SELECTION_TEXT,
CLIPBOARD_SET_SELECTION_TEXT,
)
from .exceptions import ClipboardOperationError
from .menu import Menu
from .toast import ToastWidget, ToastConfig
from .toolbar import ToolBar
from .utils import IconType, get_icon, get_size
@dataclasses.dataclass(frozen=True)
class BaseWindowConfig(object):
title: str = ""
"""窗口标题"""
icon: IconType = None
"""窗口图标"""
size: Union[Tuple[int, int], QSize] = (800, 600)
"""窗口大小"""
position: Optional[Tuple[int, int]] = None
"""窗口位置"""
always_on_top: bool = False
"""窗口是否永远置顶"""
font_family: Union[str, Sequence[str], None] = None
"""窗口使用的字体"""
font_size: Optional[int] = None
"""窗口字体的大小(px)"""
close_button: bool = True
"""是否显示关闭按钮"""
minimize_button: bool = True
"""是否显示最小化按钮"""
maximize_button: bool = True
"""是否显示最大化按钮"""
stylesheet: Optional[str] = None
"""窗口的样式表(QSS格式)"""
# noinspection PyMethodMayBeStatic
class BaseWindowEventListener(object):
"""该类为窗口事件监听器基类,用于监听`BaseWindow`类的窗口事件。开发者可以在子类中override特定的事件回调函数,以实现对特定事件的监听"""
def on_create(self, window: "BaseWindow") -> None:
"""
事件回调函数,在窗口创建后调用。
Args:
window: 发生事件的窗口
Returns:
无返回值
"""
pass
# noinspection PyUnusedLocal
def on_close(self, window: "BaseWindow") -> bool:
"""
事件回调函数,在窗口关闭时调用。
Args:
window: 发生事件的窗口
Returns:
返回一个`bool`值,用于指示是否要关闭窗口。返回`True`表示确实要关闭窗口,返回`False`将阻止窗口被关闭。默认返回`True`。
"""
return True
def on_destroy(self, window: "BaseWindow") -> None:
"""
事件回调函数,在窗口销毁后调用(注意:在该函数回调后,还将回调一次`on_hide()`)。
Args:
window: 发生事件的窗口
Returns:
无返回值
"""
pass
def on_hide(self, window: "BaseWindow") -> None:
"""
事件回调函数,在窗口被隐藏后调用(注意:在`on_destroy()`被回调后,此函数将被回调)。
Args:
window: 发生事件的窗口
Returns:
无返回值
"""
pass
def on_show(self, window: "BaseWindow") -> None:
"""
事件回调函数,在窗口显示后调用。
Args:
window: 发生事件的窗口
Returns:
无返回值
"""
pass
class SimpleWindowEventListener(BaseWindowEventListener):
"""该类为`BaseWindowEventListener`子类,用于快速创建`BaseWindowEventListener`实例。开发者可以直接在构造函数中传入要监听的事件的回调函数,
而不必手动创建`BaseWindowEventListener`的子类。
"""
def __init__(
self,
on_create: Callable[["BaseWindow"], None] = None,
on_show: Callable[["BaseWindow"], None] = None,
on_hide: Callable[["BaseWindow"], None] = None,
on_close: Callable[["BaseWindow"], bool] = None,
on_destroy: Callable[["BaseWindow"], None] = None,
):
"""
构造函数。用于创建`SimpleWindowEventListener`类实例。
Args:
on_create: 回调函数,该函数在窗口创建后调用。
on_show: 回调函数,该函数在窗口显示后回调。
on_hide: 回调函数,该函数在窗口被隐藏时回调。
on_close: 回调函数,该函数在窗口被关闭时回调。
on_destroy: 回调函数,该函数在窗口被销毁后回调。
"""
self._on_create_callback = on_create
self._on_show_callback = on_show
self._on_hide_callback = on_hide
self._on_close_callback = on_close
self._on_destroy_callback = on_destroy
def on_create(self, window: "BaseWindow") -> None:
if self._on_create_callback:
return self._on_create_callback(window)
return super().on_create(window)
def on_close(self, window: "BaseWindow") -> bool:
if self._on_close_callback:
return self._on_close_callback(window)
return super().on_close(window)
def on_destroy(self, window: "BaseWindow") -> None:
if self._on_destroy_callback:
return self._on_destroy_callback(window)
return super().on_destroy(window)
def on_hide(self, window: "BaseWindow") -> None:
if self._on_hide_callback:
return self._on_hide_callback(window)
return super().on_hide(window)
def on_show(self, window: "BaseWindow") -> None:
if self._on_show_callback:
return self._on_show_callback(window)
return super().on_show(window)
class BaseWindow(QMainWindow):
"""
`PyGUIAdapter`中所有顶级窗口的基类,定义了窗口基本的外观和逻辑,并且实现了一些公共的方法。
这些方法可以在窗口事件回调函数中或者`Action`的回调函数中调用。
"""
sig_clear_toasts = Signal()
def __init__(
self,
parent: Optional[QWidget],
config: BaseWindowConfig,
listener: Optional[BaseWindowEventListener] = None,
toolbar: Optional[ToolBar] = None,
menus: Optional[List[Union[Menu, Separator]]] = None,
):
super().__init__(parent)
self._config: BaseWindowConfig = config
self._toolbar: Optional[ToolBar] = toolbar
if menus:
menus = [*menus]
self._menus: Optional[List[Union[Menu, Separator]]] = menus
self._listener: BaseWindowEventListener = listener
self._actions: Dict[int, QAction] = {}
self._create_ui()
self.apply_configs()
self._setup_toolbar()
self._setup_menus()
self._on_create()
# noinspection PyMethodOverriding
def closeEvent(self, event):
if not self._on_close():
event.ignore()
return
self._on_cleanup()
event.accept()
self._on_destroy()
# noinspection PyPep8Naming
def showEvent(self, event):
self._on_show()
super().showEvent(event)
# noinspection PyMethodOverriding
def hideEvent(self, event):
self._on_hide()
super().hideEvent(event)
def apply_configs(self):
if self._config is None:
return
self.set_title(self._config.title)
self.set_icon(self._config.icon)
self.set_size(self._config.size)
self.set_position(self._config.position)
self.set_always_on_top(self._config.always_on_top)
self.set_font(self._config.font_family, self._config.font_size)
self.set_stylesheet(self._config.stylesheet)
self._apply_window_flags()
def set_title(self, title: str) -> None:
"""
设置窗口标题。
Args:
title: 待设置的标题
Returns:
无返回值
"""
title = title or ""
self.setWindowTitle(title)
def get_title(self) -> str:
"""
获取窗口标题。
Returns:
返回当前窗口标题
"""
return self.windowTitle()
def set_icon(self, icon: IconType) -> None:
"""
设置窗口图标。
Args:
icon: 待设置的图标
Returns:
无返回值
"""
icon = get_icon(icon) or QIcon()
self.setWindowIcon(icon)
def set_always_on_top(self, enabled: bool) -> None:
"""
设置窗口是否总是置顶。
Args:
enabled: 是否总是置顶
Returns:
无返回值
"""
flags = self.windowFlags()
if enabled:
flags |= Qt.WindowStaysOnTopHint
else:
flags &= ~Qt.WindowStaysOnTopHint
self.setWindowFlags(flags)
def is_always_on_top(self) -> bool:
"""
判断窗口是否总是置顶。
Returns:
返回`True`代表窗口当前处于总是置顶状态。
"""
return bool(self.windowFlags() & Qt.WindowStaysOnTopHint)
def set_size(self, size: Union[Tuple[int, int], QSize]) -> None:
"""
设置窗口尺寸。
Args:
size: 目标尺寸。
Returns:
无返回值
"""
size = get_size(size)
if not size:
raise ValueError(f"invalid size: {size}")
self.resize(size)
def get_size(self) -> Tuple[int, int]:
"""
获取窗口当前尺寸。
Returns:
返回窗口当前尺寸。
"""
size = self.size()
return size.width(), size.height()
def set_position(self, position: Optional[Tuple[int, int]]) -> None:
"""
设置窗口在屏幕上的位置。
Args:
position: 目标位置。
Returns:
无返回值
"""
if not position:
return
if len(position) != 2:
raise ValueError(f"invalid position: {position}")
self.move(*position)
def get_position(self) -> Tuple[int, int]:
"""
获取窗口位置。
Returns:
返回窗口当前在屏幕上的位置。
"""
pos = self.pos()
return pos.x(), pos.y()
def set_font(self, font_family: Union[str, Sequence[str]], font_size: int) -> None:
"""
设置窗口字体。
Args:
font_family: 字体名称
font_size: 字体大小(px)
Returns:
无返回值
"""
font = self.font()
if not font_family:
pass
elif isinstance(font_family, str):
font.setFamily(font_family)
elif isinstance(font_family, Sequence):
font = self.font()
font.setFamilies(font_family)
else:
raise TypeError(f"invalid font_family type: {type(font_family)}")
if font_size and font_size > 0:
font.setPixelSize(font_size)
# font.setPointSize(font_size)
self.setFont(font)
def get_font_size(self) -> int:
"""
获取窗口字体大小(px)。
Returns:
返回当前窗口字体大小。
"""
return self.font().pointSize()
def get_font_family(self) -> str:
"""
获取当前窗口字体系列名称。
Returns:
返回当前窗口字体系列名称(以字符串形式)。
"""
return self.font().family()
def get_font_families(self) -> Sequence[str]:
"""
获取当前窗口字体系列名称。
Returns:
返回当前窗口字体系列名称(以列表形式)。
"""
return self.font().families()
def set_stylesheet(self, stylesheet: Optional[str]) -> None:
"""
为窗口设置样式表(QSS)格式。
Args:
stylesheet: 样式表
Returns:
无返回值
"""
if not stylesheet:
return
self.setStyleSheet(stylesheet)
def get_stylesheet(self) -> str:
"""
获取窗口当前样式表。
Returns:
返回窗口当前样式表。
"""
return self.styleSheet()
def has_action(self, action: Action) -> bool:
"""
检测指定`Action`是否被添加到当前窗口中。
Args:
action: 待检测的`Action`
Returns:
返回`True`代表指定`Action`已被添加到当前窗口中,否则返回`False`。
"""
return self._find_action(action) is not None
def is_action_checkable(self, action: Action) -> Optional[bool]:
"""
检测指定`Action`是否为“可选中”的。
Args:
action: 待检测的`Action`
Returns:
返回`True`代表指定`Action`为“可选中”的,否则返回`False`。若未找到指定`Action`,则返回`None`。
"""
action = self._find_action(action)
if not action:
return None
return action.isCheckable()
def is_action_checked(self, action: Action) -> Optional[bool]:
"""
检测指定`Action`是否处于“选中”状态。
Args:
action: 待检测的`Action`
Returns:
返回`True`代表指定`Action`当前为“选中”状态的,否则返回`False`。若未找到指定`Action`,则返回`None`。
"""
action = self._find_action(action)
if not action:
return None
return action.isChecked()
def set_action_state(self, action: Action, checked: bool) -> Optional[bool]:
"""
设置`Action`当前状态。
Args:
action: 目标`Action`
checked: 目标状态
Returns:
返回设置之前的状态。若未找到目标`Action`,则返回`None`。
"""
action = self._find_action(action)
if not action:
return None
old_state = action.isChecked()
action.setChecked(checked)
return old_state
def toggle_action_state(self, action: Action) -> Optional[bool]:
"""
切换目标`Action`的当前状态。
Args:
action: 目标`Action`
Returns:
返回切换之前的状态。若未找到目标`Action`,则返回`None`。
"""
action = self._find_action(action)
if not action:
return None
old_state = action.isChecked()
action.toggle()
return old_state
def get_action_state(self, action: Action) -> Optional[bool]:
"""
检查目标`Action`的当前状态
Args:
action: 目标`Action`
Returns:
返回目标`Action`的当前状态。若未找到目标`Action`,则返回`None`。
"""
action = self._find_action(action)
if action is None:
return None
return action.isChecked()
def set_action_enabled(self, action: Action, enabled: bool) -> Optional[bool]:
"""
设置目标`Action`的启用状态。
Args:
action: 目标`Action`
enabled: 目标状态
Returns:
返回设置之前的启用状态。若未找到目标`Action`,则返回`None`。
"""
action = self._find_action(action)
if not action:
return None
old_state = action.isEnabled()
action.setEnabled(enabled)
return old_state
def is_action_enabled(self, action: Action) -> Optional[bool]:
"""
检查目标`Action`当前的启用状态。
Args:
action: 目标`Action`
Returns:
返回目标`Action`当前的启用状态。若未找到目标`Action`,则返回`None`。
"""
action = self._find_action(action)
if not action:
return None
return action.isEnabled()
def _find_action(self, action: Action) -> Optional[QAction]:
return self._actions.get(id(action), None)
@staticmethod
def get_clipboard_text() -> str:
"""
获取剪贴板内容。
Returns:
返回当前剪贴板文本。
"""
clipboard = QApplication.clipboard()
return clipboard.text()
@staticmethod
def set_clipboard_text(text: str) -> None:
"""
设置剪贴板内容。
Args:
text: 要设置到剪贴板中的文本
Returns:
无返回值
"""
clipboard = QApplication.clipboard()
clipboard.setText(text)
@staticmethod
def get_selection_text() -> Optional[str]:
clipboard = QApplication.clipboard()
return clipboard.text(mode=QClipboard.Selection)
@staticmethod
def set_selection_text(text: str):
clipboard = QApplication.clipboard()
clipboard.setText(text, mode=QClipboard.Selection)
@staticmethod
def supports_selection() -> bool:
return QApplication.clipboard().supportsSelection()
@staticmethod
def owns_clipboard() -> bool:
return QApplication.clipboard().ownsClipboard()
@staticmethod
def owns_selection() -> bool:
return QApplication.clipboard().ownsSelection()
def on_clipboard_operation(self, future: Future, operation: int, data: object):
if operation == CLIPBOARD_GET_TEXT:
text = self.get_clipboard_text()
future.set_result(text)
return
if operation == CLIPBOARD_SET_TEXT:
if not isinstance(data, str):
raise ClipboardOperationError(
operation, f"data must be a str, got {data}"
)
self.set_clipboard_text(data)
future.set_result(None)
return
if operation == CLIPBOARD_GET_SELECTION_TEXT:
text = self.get_selection_text()
future.set_result(text)
return
if operation == CLIPBOARD_SET_SELECTION_TEXT:
if not isinstance(data, str):
raise ClipboardOperationError(
operation, f"data must be a str, got {data}"
)
self.set_selection_text(data)
future.set_result(None)
return
if operation == CLIPBOARD_SUPPORTS_SELECTION:
future.set_result(self.supports_selection())
return
if operation == CLIPBOARD_OWNS_CLIPBOARD:
future.set_result(self.owns_clipboard())
return
if operation == CLIPBOARD_OWNS_SELECTION:
future.set_result(self.owns_selection())
return
raise ClipboardOperationError(
operation, f"invalid clipboard operation: {operation}"
)
def show_toast(
self,
message: str,
duration: int = 2000,
config: Optional[ToastConfig] = None,
clear: bool = False,
) -> None:
"""
显示一条toast消息。
Args:
message: 待显示的消息
duration: 消息显示的时长,单位毫秒
config: toast的配置
clear: 在显示当前消息前,是否清除之前发出的消息
Returns:
无返回值
"""
if clear:
self.clear_toasts()
toast = ToastWidget(self, message, duration, config=config)
toast.sig_toast_finished.connect(self._on_toast_finished)
# noinspection PyUnresolvedReferences
self.sig_clear_toasts.connect(toast.finish)
toast.start()
def clear_toasts(self) -> None:
"""
清除之前发出的toast消息。
Returns:
无返回值
"""
# noinspection PyUnresolvedReferences
self.sig_clear_toasts.emit()
def _on_toast_finished(self):
w = self.sender()
if not isinstance(w, ToastWidget):
return
# noinspection PyUnresolvedReferences
self.sig_clear_toasts.disconnect(w.finish)
w.sig_toast_finished.disconnect(self._on_toast_finished)
w.deleteLater()
del w
def _setup_toolbar(self):
# create toolbar (if toolbar config provided)
if self._toolbar:
self._create_toolbar(toolbar_config=self._toolbar)
def _setup_menus(self):
# create menu (if menu config provided)
if self._menus:
self._create_menus(menus=self._menus)
def _create_toolbar(self, toolbar_config: ToolBar):
toolbar = QToolBar(self)
toolbar.setMovable(toolbar_config.moveable)
toolbar.setFloatable(toolbar_config.floatable)
size = get_size(toolbar_config.icon_size)
if size:
toolbar.setIconSize(size)
if toolbar_config.allowed_areas:
toolbar.setAllowedAreas(toolbar_config.allowed_areas)
if toolbar_config.button_style is not None:
toolbar.setToolButtonStyle(toolbar_config.button_style)
if toolbar_config.actions:
self._add_toolbar_actions(toolbar=toolbar, actions=toolbar_config.actions)
toolbar_area = toolbar_config.initial_area
if toolbar_area is None:
# noinspection PyUnresolvedReferences
toolbar_area = Qt.TopToolBarArea
self.addToolBar(toolbar_area, toolbar)
self._toolbar = toolbar
def _add_toolbar_actions(
self, toolbar: QToolBar, actions: List[Union[Action, Separator]]
):
for action in actions:
if isinstance(action, Separator):
toolbar.addSeparator()
continue
action = self._create_action(action)
toolbar.addAction(action)
def _create_menus(self, menus: Sequence[Menu]):
menubar = self.menuBar()
for menu in menus:
if isinstance(menu, Separator):
menubar.addSeparator()
continue
menu = self._create_menu(menu)
menubar.addMenu(menu)
# noinspection PyArgumentList
def _create_menu(self, menu: Menu) -> QMenu:
q_menu = QMenu(self)
q_menu.setTitle(menu.title)
exclusive_group = None
if menu.exclusive:
exclusive_group = QActionGroup(self)
exclusive_group.setExclusive(True)
for action in menu.actions:
if isinstance(action, Separator):
q_menu.addSeparator()
continue
if isinstance(action, Action):
action = self._create_action(action)
if action.isCheckable() and exclusive_group:
exclusive_group.addAction(action)
q_menu.addAction(action)
elif isinstance(action, Menu):
submenu = self._create_menu(action)
q_menu.addMenu(submenu)
else:
raise ValueError(f"invalid action type: {type(action)}")
return q_menu
def _create_action(self, action: Action) -> QAction:
aid = id(action)
# reuse action if already created
if aid in self._actions:
return self._actions[aid]
q_action = QAction(self)
if action.text:
q_action.setText(action.text)
if action.icon:
q_action.setIcon(get_icon(action.icon))
if action.icon_text:
q_action.setIconText(action.icon_text)
q_action.setAutoRepeat(action.auto_repeat)
q_action.setEnabled(action.enabled)
q_action.setCheckable(action.checkable)
q_action.setChecked(action.checked)
if action.shortcut:
q_action.setShortcut(action.shortcut)
if action.shortcut_context is not None:
q_action.setShortcutContext(action.shortcut_context)
if action.tooltip:
q_action.setToolTip(action.tooltip)
if action.status_tip:
q_action.setStatusTip(action.status_tip)
if action.whats_this:
q_action.setWhatsThis(action.whats_this)
if action.priority is not None:
q_action.setPriority(action.priority)
if action.menu_role is not None:
q_action.setMenuRole(action.menu_role)
def _triggered():
if action.on_triggered is not None:
action.on_triggered(self, action)
def _toggled():
if action.on_toggled is not None:
action.on_toggled(self, action, q_action.isChecked())
# noinspection PyUnresolvedReferences
q_action.triggered.connect(_triggered)
# noinspection PyUnresolvedReferences
q_action.toggled.connect(_toggled)
self._actions[aid] = q_action
return q_action
def _on_create(self):
if not self._listener:
return
self._listener.on_create(self)
def _on_close(self) -> bool:
if not self._listener:
should_close = True
else:
should_close = self._listener.on_close(self)
return should_close
def _on_destroy(self):
if not self._listener:
return
self._listener.on_destroy(self)
def _on_hide(self):
if not self._listener:
return
self._listener.on_hide(self)
def _on_show(self):
if not self._listener:
return
self._listener.on_show(self)
def _on_cleanup(self):
self.clear_toasts()
self._clear_actions()
def _clear_actions(self):
for action in self._actions.values():
self.removeAction(action)
action.deleteLater()
self._actions.clear()
del self._actions
@abstractmethod
def _create_ui(self):
pass
def _apply_window_flags(self):
flags = self.windowFlags()
if self._config.close_button:
flags |= Qt.WindowCloseButtonHint
else:
flags &= ~Qt.WindowCloseButtonHint
if self._config.minimize_button:
flags |= Qt.WindowMinimizeButtonHint
else:
flags &= ~Qt.WindowMinimizeButtonHint
if self._config.maximize_button:
flags |= Qt.WindowMaximizeButtonHint
else:
flags &= ~Qt.WindowMaximizeButtonHint
self.setWindowFlags(flags)
| 26,819 | Python | .py | 729 | 23.648834 | 99 | 0.584723 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,452 | bundle.py | zimolab_PyGUIAdapter/pyguiadapter/bundle.py | """
@Time : 2024.10.27
@File : bundle.py
@Author : zimolab
@Project : PyGUIAdapter
@Desc : 定义了FnBundle类,用于封装函数信息、参数配置、窗口配置、窗口事件监听器、窗口工具栏、窗口菜单等信息。方便传参。仅限于内部使用。
"""
import dataclasses
from typing import Type, Tuple, Dict, Optional, List, Union
from .action import Separator
from .fn import FnInfo
from .menu import Menu
from .paramwidget import BaseParameterWidget, BaseParameterWidgetConfig
from .toolbar import ToolBar
from .window import BaseWindowEventListener
from .windows.fnexec import FnExecuteWindowConfig
@dataclasses.dataclass
class FnBundle(object):
fn_info: FnInfo
widget_configs: Dict[
str, Tuple[Type[BaseParameterWidget], BaseParameterWidgetConfig]
]
window_config: FnExecuteWindowConfig
window_listener: Optional[BaseWindowEventListener]
window_toolbar: Optional[ToolBar]
window_menus: Optional[List[Union[Menu, Separator]]]
| 1,008 | Python | .py | 26 | 31.692308 | 78 | 0.796512 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,453 | executor.py | zimolab_PyGUIAdapter/pyguiadapter/executor.py | """
@Time : 2024.10.20
@File : executor.py
@Author : zimolab
@Project : PyGUIAdapter
@Desc : 定义了函数执行器的抽象基类,所有函数执行器都应该继承自该类并实现相应抽象方法。
"""
from abc import abstractmethod
from typing import Any, Dict, Optional
from qtpy.QtCore import QObject
from .fn import FnInfo
class ExecuteStateListener(object):
def before_execute(self, fn_info: FnInfo, arguments: Dict[str, Any]) -> None:
pass
def on_execute_start(self, fn_info: FnInfo, arguments: Dict[str, Any]) -> None:
pass
def on_execute_finish(self, fn_info: FnInfo, arguments: Dict[str, Any]) -> None:
pass
def on_execute_result(
self, fn_info: FnInfo, arguments: Dict[str, Any], result: Any
) -> None:
pass
def on_execute_error(
self, fn_info: FnInfo, arguments: Dict[str, Any], exception: Exception
) -> None:
pass
class BaseFunctionExecutor(QObject):
def __init__(
self, parent: Optional[QObject], listener: Optional[ExecuteStateListener]
):
super().__init__(parent)
self._listener = listener
@property
def listener(self) -> Optional[ExecuteStateListener]:
return self._listener
@abstractmethod
def execute(self, fn_info: FnInfo, arguments: Dict[str, Any]):
pass
@property
@abstractmethod
def is_executing(self) -> bool:
pass
@abstractmethod
def try_cancel(self):
pass
@property
@abstractmethod
def is_cancelled(self) -> bool:
pass
| 1,590 | Python | .py | 49 | 25.326531 | 84 | 0.662976 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,454 | toast.py | zimolab_PyGUIAdapter/pyguiadapter/toast.py | """
@Time : 2024.10.20
@File : toast.py
@Author : zimolab
@Project : PyGUIAdapter
@Desc : 实现了简单的toast提示框
"""
import dataclasses
from typing import Optional, Union, Tuple, Dict, Sequence
from qtpy.QtCore import Signal, QTimer, QMutex, Qt, QPropertyAnimation
from qtpy.QtWidgets import QWidget, QLabel
from .constants.font import FONT_FAMILY, FONT_HUGE
from .constants.color import COLOR_TOAST_BACKGROUND_CLASSIC, COLOR_TOAST_TEXT_CLASSIC
from .utils import move_window
DEFAULT_POSITION = (0.5, 0.9)
TextAlignment = Union[Qt.AlignmentFlag, int]
"""文字对齐方式"""
AlignCenter = Qt.AlignVCenter | Qt.AlignHCenter
"""居中对齐"""
AlignLeft = Qt.AlignLeft | Qt.AlignVCenter
"""左对齐"""
AlignRight = Qt.AlignRight | Qt.AlignVCenter
"""右对齐"""
@dataclasses.dataclass(frozen=True)
class ToastConfig(object):
"""
Toast控件配置类
"""
opacity: float = 0.9
"""不透明度"""
background_color: str = COLOR_TOAST_BACKGROUND_CLASSIC
"""背景颜色"""
text_color: str = COLOR_TOAST_TEXT_CLASSIC
"""文字颜色"""
text_padding: int = 50
"""文字边距"""
text_alignment: Optional[TextAlignment] = None
"""文字对齐方式"""
font_family: Union[Sequence[str], str] = FONT_FAMILY
"""字体"""
font_size: Optional[int] = FONT_HUGE
"""字体大小"""
position: Optional[Tuple[Union[int, float, None], Union[int, float, None]]] = (
DEFAULT_POSITION
)
"""显示位置,可以使用百分比或绝对坐标,比如`(0.5, 0.5)`表示在屏幕中心显示,`(100, 100)`表示在屏幕坐标x=100 y=100处显示"""
fixed_size: Optional[Tuple[int, int]] = None
"""固定尺寸"""
fade_out: Optional[int] = None
"""淡出时间"""
styles: Optional[Dict[str, str]] = None
"""额外样式"""
class ToastWidget(QLabel):
sig_toast_finished = Signal()
def __init__(
self,
parent: Optional[QWidget],
message: str,
duration: int,
config: Optional[ToastConfig] = None,
):
super().__init__(parent)
self._message: str = message
self._duration: int = duration
self._config: ToastConfig = config or ToastConfig()
self._lock = QMutex()
self._closing: bool = False
self._fadeout_animation: Optional[QPropertyAnimation] = None
if self._config.fade_out:
self._fadeout_animation = QPropertyAnimation(self, b"windowOpacity")
self._fadeout_animation.setDuration(self._config.fade_out)
self._fadeout_animation.setStartValue(self._config.opacity)
self._fadeout_animation.setEndValue(0.0)
# noinspection PyUnresolvedReferences
self._fadeout_animation.finished.connect(self.close)
self._setup_ui()
self._close_timer: Optional[QTimer] = None
if self._duration > 0:
self._close_timer = QTimer(self)
self._close_timer.setSingleShot(True)
# noinspection PyUnresolvedReferences
self._close_timer.timeout.connect(self._on_finish)
self.hide()
def _setup_ui(self):
# set message text
self.setText(self._message)
# set window attributes
flags = self.windowFlags()
flags |= Qt.Window
flags |= Qt.WindowStaysOnTopHint
flags |= Qt.FramelessWindowHint
flags |= Qt.WindowTransparentForInput
self.setWindowFlags(flags)
self.setFocusPolicy(Qt.NoFocus)
self.setAttribute(Qt.WA_ShowWithoutActivating, True)
self.setAttribute(Qt.WA_TransparentForMouseEvents, True)
self.setWordWrap(True)
stylesheet = self._stylesheet()
self.setStyleSheet(stylesheet)
if self._config.text_alignment:
self.setAlignment(self._config.text_alignment)
if self._config.fixed_size:
self.setFixedSize(self._config.fixed_size[0], self._config.fixed_size[1])
else:
self.adjustSize()
move_window(self, *self._config.position)
self.setWindowOpacity(self._config.opacity)
def start(self):
self.show()
if self._close_timer:
self._close_timer.start(self._duration)
def finish(self):
if self._close_timer:
self._close_timer.stop()
self._on_finish()
def _on_finish(self):
self._lock.lock()
if self._closing:
self._lock.unlock()
return
self._closing = True
self._lock.unlock()
if self._fadeout_animation:
self._fadeout_animation.start()
else:
self.hide()
self.close()
def closeEvent(self, event):
self._lock.lock()
if not self._closing:
event.ignore()
self._lock.unlock()
return
self._lock.unlock()
# noinspection PyUnresolvedReferences
self._close_timer.timeout.disconnect(self._on_finish)
if self._fadeout_animation:
# noinspection PyUnresolvedReferences
self._fadeout_animation.finished.disconnect(self.close)
event.accept()
# noinspection PyUnresolvedReferences
self.sig_toast_finished.emit()
def _stylesheet(self) -> str:
more_styles = self._config.styles or {}
style_dict = {
"background-color": f'"{self._config.background_color}"',
"color": f'"{self._config.text_color}"',
"font-size": f"{self._config.font_size}px",
"font-family": f'"{self._config.font_family}"',
"padding": f"{self._config.text_padding}",
**more_styles,
}
return "\n".join(f"{k}:{v};" for k, v in style_dict.items())
| 5,789 | Python | .py | 153 | 28.594771 | 85 | 0.626977 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,455 | toolbar.py | zimolab_PyGUIAdapter/pyguiadapter/toolbar.py | """
@Time : 2024.10.20
@File : toolbar.py
@Author : zimolab
@Project : PyGUIAdapter
@Desc : 定义了工具栏配置类和相关常量。
"""
import dataclasses
from typing import Optional, List, Union, Tuple
from qtpy.QtCore import Qt, QSize
from .action import Action, Separator
ToolBarArea = Qt.ToolBarArea
TopToolBarArea = ToolBarArea.TopToolBarArea
BottomToolBarArea = ToolBarArea.BottomToolBarArea
LeftToolBarArea = ToolBarArea.LeftToolBarArea
RightToolBarArea = ToolBarArea.RightToolBarArea
ToolBarAreas = Union[ToolBarArea, int]
AllToolBarAreas = Qt.AllToolBarAreas
ToolButtonStyle = Qt.ToolButtonStyle
ToolButtonIconOnly = ToolButtonStyle.ToolButtonIconOnly
ToolButtonTextBesideIcon = ToolButtonStyle.ToolButtonTextBesideIcon
ToolButtonTextUnderIcon = ToolButtonStyle.ToolButtonTextUnderIcon
ToolButtonFollowStyle = ToolButtonStyle.ToolButtonFollowStyle
ToolButtonTextOnly = ToolButtonStyle.ToolButtonTextOnly
@dataclasses.dataclass(frozen=True)
class ToolBar(object):
"""该类用于配置窗口上的工具栏"""
actions: List[Union[Action, Separator]]
"""要添加到工具栏中的动作(`Action`)或分隔符(`Separator`)列表。在工具栏中,动作`Action`以工具栏按钮的形式出现。"""
moveable: bool = True
"""工具栏是否可以移动。"""
floatable: bool = True
"""工具栏是否可以漂浮在主窗口之外。"""
icon_size: Union[int, Tuple[int, int], QSize, None] = None
"""工具栏按钮的图标大小,"""
initial_area: Optional[ToolBarArea] = None
"""工具栏在窗口上的初始位置。"""
allowed_areas: Optional[ToolBarAreas] = None
"""窗口上允许工具栏停靠的位置。"""
button_style: Optional[ToolButtonStyle] = None
"""工具栏按的样式。"""
def remove_action(self, action: Union[str, Action, Separator]):
if isinstance(action, str):
for action_ in self.actions:
if isinstance(action_, Action):
if action_.text == action:
action = action_
break
if action in self.actions:
self.actions.remove(action)
return
if action in self.actions:
self.actions.remove(action)
return
| 2,314 | Python | .py | 54 | 31.851852 | 79 | 0.715816 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,456 | fn.py | zimolab_PyGUIAdapter/pyguiadapter/fn.py | """
@Time : 2024.10.20
@File : fn.py
@Author : zimolab
@Project : PyGUIAdapter
@Desc : 对函数进行了抽象和建模。仅限内部使用。
"""
import dataclasses
from typing import Callable, Literal, Any, Dict, List, Type, Optional, ForwardRef
from .utils import IconType
@dataclasses.dataclass
class ParameterInfo(object):
default_value: Any
type: Type
typename: str
type_args: List[Any] = dataclasses.field(default_factory=list)
description: Optional[str] = None
@dataclasses.dataclass
class FnInfo(object):
fn: Callable
display_name: str
document: str = ""
document_format: Literal["markdown", "html", "plaintext"] = "markdown"
icon: IconType = None
group: Optional[str] = None
parameters: Dict[str, ParameterInfo] = dataclasses.field(default_factory=dict)
cancelable: bool = False
executor: Optional[ForwardRef("BaseFunctionExecutor")] = None
| 925 | Python | .py | 28 | 28.464286 | 82 | 0.728019 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,457 | extend_types.py | zimolab_PyGUIAdapter/pyguiadapter/extend_types.py | """
@Time : 2024.10.20
@File : extend_types.py
@Author : zimolab
@Project : PyGUIAdapter
@Desc : 定义了一些语义化类型。
"""
# noinspection PyPep8Naming
class text_t(str):
pass
# noinspection PyPep8Naming
class int_t(int):
pass
# noinspection PyPep8Naming
class float_t(float):
pass
# noinspection PyPep8Naming
class file_t(str):
pass
# noinspection PyPep8Naming
class files_t(list):
pass
# noinspection PyPep8Naming
class directory_t(str):
pass
dir_t = directory_t
# noinspection PyPep8Naming
class choice_t(object):
pass
# noinspection PyPep8Naming
class choices_t(list):
pass
# noinspection PyPep8Naming
class int_slider_t(int):
pass
# noinspection PyPep8Naming
class int_dial_t(int):
pass
# noinspection PyPep8Naming
class color_t(object):
pass
# noinspection PyPep8Naming
class color_tuple_t(tuple):
pass
# noinspection PyPep8Naming
class color_hex_t(str):
pass
# noinspection PyPep8Naming
class key_sequence_t(str):
pass
# noinspection PyPep8Naming
class string_list_t(list):
pass
# noinspection PyPep8Naming
class plain_dict_t(dict):
pass
# noinspection PyPep8Naming
class json_obj_t(object):
pass
| 1,229 | Python | .py | 59 | 17.694915 | 27 | 0.767986 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,458 | menu.py | zimolab_PyGUIAdapter/pyguiadapter/menu.py | """
@Time : 2024.10.20
@File : menu.py
@Author : zimolab
@Project : PyGUIAdapter
@Desc : 定义菜单配置类
"""
import dataclasses
from typing import List, Union
from .action import Action, Separator
@dataclasses.dataclass(frozen=True)
class Menu(object):
"""该类用于配置窗口菜单栏上的菜单。"""
title: str
"""菜单的标题。"""
actions: List[Union[Action, Separator, "Menu"]]
"""菜单下的菜单项(`Action`)、分隔符(`Separator`)或子菜单(`Menu`)"""
separators_collapsible: bool = True
"""是否将连续的分隔符合并。为`True`时连续分隔符将被合并为一个,同时,位于菜单开头或结尾的分隔符也会被隐藏。"""
tear_off_enabled: bool = True
"""菜单可以被“撕下”。为`True`时,菜单将包含一个特殊的“撕下”项(通常显示为菜单顶部的虚线),当触发它时,会创建一个菜单的副本。这个“撕下”的副本
会存在于一个单独的窗口中,并且包含与原始菜单相同的菜单项。"""
exclusive: bool = False
"""是否将菜单下的菜单项(`Action`)添加到一个互斥组中。只有当前菜单下`checkable`属性为`True`的菜单项(`Action`)才会被添加的互斥组中。"""
def remove_action(self, action: Union[str, Action, Separator, "Menu"]):
if isinstance(action, str):
for action_ in self.actions:
if isinstance(action_, Action):
if action_.text == action:
action = action_
break
if isinstance(action_, Menu):
if action_.title == action:
action = action_
break
if action in self.actions:
self.actions.remove(action)
return
if action in self.actions:
self.actions.remove(action)
return
| 1,986 | Python | .py | 41 | 27.585366 | 92 | 0.598753 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,459 | action.py | zimolab_PyGUIAdapter/pyguiadapter/action.py | """
@Time : 2024.10.20
@File : action.py
@Author : zimolab
@Project : PyGUIAdapter
@Desc : 定义了动作(`Action`)配置类、分割符(`Separator`)类以及相关常量。
"""
import dataclasses
from typing import Optional, Callable, ForwardRef
from qtpy.QtCore import Qt
from qtpy.QtWidgets import QAction
from .utils import IconType
Priority = QAction.Priority
HighPriority = QAction.HighPriority
NormalPriority = QAction.NormalPriority
LowPriority = QAction.LowPriority
MenuRole = QAction.MenuRole
NoRole = QAction.NoRole
TextHeuristicRole = QAction.TextHeuristicRole
ApplicationSpecificRole = QAction.ApplicationSpecificRole
AboutQtRole = QAction.AboutQtRole
AboutRole = QAction.AboutRole
PreferencesRole = QAction.PreferencesRole
QuitRole = QAction.QuitRole
ShortcutContext = Qt.ShortcutContext
WidgetShortcut = Qt.WidgetShortcut
WidgetWithChildrenShortcut = Qt.WidgetWithChildrenShortcut
WindowShortcut = Qt.WindowShortcut
ApplicationShortcut = Qt.ApplicationShortcut
BaseWindow_ = ForwardRef("BaseWindow")
Action_ = ForwardRef("Action")
ActionTriggeredCallback = Callable[[BaseWindow_, Action_], None]
ActionToggledCallback = Callable[[BaseWindow_, Action_, bool], None]
@dataclasses.dataclass
class Action(object):
"""该类用于创建动作(`Action`),在工具栏(`ToolBar`)中一个`Action`代表一个工具栏按钮,在菜单(`Menu`)中,一个`Action`代表一个菜单项。"""
text: str
"""动作(`Action`)的描述性文本。"""
on_triggered: Optional[ActionTriggeredCallback] = None
"""回调函数,在动作(`Action`)被触发时回调。"""
on_toggled: Optional[ActionToggledCallback] = None
"""回调函数,在动作(`Action`)的`checked`状态发生切换时回调。"""
icon: IconType = None
"""动作(`Action`)的图标。"""
icon_text: Optional[str] = None
"""动作(`Action`)的图标文本。"""
auto_repeat: bool = True
"""此属性表示动作(`Action`)是否可以自动重复。如果设置为`True`,并且系统启用了键盘自动重复功能,那么当用户持续按下键盘快捷键组合时,该动作将自动重复。"""
enabled: bool = True
"""动作(`Action`)是否处于启用状态。"""
checkable: bool = False
"""动作(`Action`)是否为**`可选中动作`**。`可选中动作`具有`选中`和`未选中`两种状态,在状态发生切换时,将触发`on_toggled`回调函数。"""
checked: bool = False
"""动作(`Action`)是否处于`选中`状态。"""
shortcut: Optional[str] = None
"""动作(`Action`)的快捷键。"""
shortcut_context: Optional[ShortcutContext] = None
"""动作(`Action`)快捷键的上下文。"""
tooltip: Optional[str] = None
"""动作(`Action`)的工具提示,工具提示是在用户将鼠标悬停在动作上时显示的额外信息。"""
whats_this: Optional[str] = None
"""动作(`Action`)的“What’s This?” 帮助文本。"""
status_tip: Optional[str] = None
"""动作(`Action`)的状态提示文本,状态提示文本将显示在动作所在窗口的状态栏中。"""
priority: Optional[Priority] = None
"""动作(`Action`)在用户界面的优先级。"""
menu_role: Optional[MenuRole] = None
"""动作(`Action`)菜单角色(menu role)。在macOS应用程序菜单中,每个动作都有一个角色,该角色指示了动作在菜单中的用途。默认情况下,所有动作
都具有TextHeuristicRole角色,这意味着动作是根据其文本内容被添加到菜单中的"""
@dataclasses.dataclass(frozen=True)
class Separator(object):
"""代表了一个分割符,开发者可以用其来分割工具栏上和菜单栏上的动作(`Action`)"""
pass
| 3,855 | Python | .py | 73 | 35.328767 | 96 | 0.741462 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,460 | paramwidget.py | zimolab_PyGUIAdapter/pyguiadapter/paramwidget.py | """
@Time : 2024.10.20
@File : paramwidget.py
@Author : zimolab
@Project : PyGUIAdapter
@Desc : 定义了参数控件基类和配置基类。
"""
import dataclasses
from abc import abstractmethod
from inspect import isclass
from typing import Any, Type, TypeVar, Optional
from qtpy.QtWidgets import QWidget
from .fn import ParameterInfo
DEFAULT_VALUE_DESCRIPTION = "use default value: {}"
@dataclasses.dataclass(frozen=True)
class BaseParameterWidgetConfig(object):
"""
参数控件配置基类。提供了所有参数控件共有的可配置属性。
"""
default_value: Any = None
"""控件的默认值。"""
label: Optional[str] = None
"""控件的标签。若不指定此属性,则使用参数名作为标签。"""
description: Optional[str] = None
"""控件的描述文本。若不指定此属性,则从尝试从函数的docstring中获取对应参数的描述文本。"""
default_value_description: Optional[str] = DEFAULT_VALUE_DESCRIPTION
"""使用默认值复选框的描述文本。当default_value为None或开发者明确指定显示默认值复选框时,默认值复选框才会显示。"""
group: Optional[str] = None
"""参数分组名称。为None时,参见将被添加到默认分组。"""
stylesheet: Optional[str] = None
"""参数控件的样式表。"""
@classmethod
@abstractmethod
def target_widget_class(cls) -> Type["BaseParameterWidget"]:
"""
目标控件类,即本配置类适用的参数控件类。子类必须实现此方法。
Returns:
目标控件类
"""
pass
@classmethod
def new(cls, **kwargs) -> "BaseParameterWidgetConfig":
return cls(**kwargs)
_T = TypeVar("_T", bound=BaseParameterWidgetConfig)
class BaseParameterWidget(QWidget):
"""
参数控件基类。定义了所有参数控件共有的接口。
"""
ConfigClass: Type[_T] = NotImplemented
"""参数控件对应的配置类。必须为BaseParameterWidgetConfig的子类。必须在子类中实现。"""
def __init__(
self,
parent: Optional[QWidget],
parameter_name: str,
config: BaseParameterWidgetConfig,
):
"""
构造函数。
Args:
parent: 父控件
parameter_name: 参数名
config: 参数控件配置
"""
super().__init__(parent)
self._config = config
self.__parameter_name = parameter_name
self.__default_value = self._config.default_value
self.__label = self._config.label
self.__description = self._config.description
self.__default_value_description = self._config.default_value_description
if self._config.stylesheet:
self.setStyleSheet(self._config.stylesheet)
@property
def parameter_name(self) -> str:
return self.__parameter_name
@property
def default_value(self) -> Any:
return self.__default_value
@property
def label(self) -> str:
if not self.__label:
return self.parameter_name
return self.__label
@label.setter
def label(self, value: str):
self.__label = value
@property
def description(self) -> str:
return self.__description or ""
@description.setter
def description(self, value: str):
self.__description = value
@property
def default_value_description(self) -> str:
if self.__default_value_description is None:
return DEFAULT_VALUE_DESCRIPTION
return self.__default_value_description
@default_value_description.setter
def default_value_description(self, value: str):
self.__default_value_description = value
@property
def config(self) -> _T:
return self._config
@abstractmethod
def get_value(self) -> Any:
"""
从控件获取参数值。子类必须实现此方法。
Returns:
参数值
"""
pass
@abstractmethod
def set_value(self, value: Any) -> None:
"""
设置参数值。子类必须实现此方法。
Args:
value: 参数值
Returns:
无返回值
"""
pass
@abstractmethod
def build(self) -> "BaseParameterWidget":
"""
构建参数控件。子类必须实现此方法。
Returns:
参数控件实例
"""
pass
def on_parameter_error(self, parameter_name: str, error: Any) -> None:
"""
参数错误时回调。子类可重写此方法。
Args:
parameter_name: 参数名
error: 错误信息
Returns:
无返回值
"""
pass
def on_clear_parameter_error(self, parameter_name: Optional[str]) -> None:
"""
清除参数错误时回调。子类可重写此方法。
Args:
parameter_name: 参数名,若为None,表示清除所有参数错误。
Returns:
无返回值
"""
pass
@classmethod
def new(
cls,
parent: Optional[QWidget],
parameter_name: str,
config: BaseParameterWidgetConfig,
):
return cls(parent, parameter_name, config).build()
# noinspection PyUnusedLocal
@classmethod
def on_post_process_config(
cls,
config: BaseParameterWidgetConfig,
parameter_name: str,
parameter_info: ParameterInfo,
) -> BaseParameterWidgetConfig:
return config
def is_parameter_widget_class(o: Any) -> bool:
return o is not None and isclass(o) and issubclass(o, BaseParameterWidget)
| 5,751 | Python | .py | 167 | 22.035928 | 81 | 0.621264 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,461 | exceptions.py | zimolab_PyGUIAdapter/pyguiadapter/exceptions.py | """
@Time : 2024.10.20
@File : exceptions.py
@Author : zimolab
@Project : PyGUIAdapter
@Desc : 自定义异常类。
"""
class ParameterError(Exception):
def __init__(self, parameter_name: str, message: str):
self._parameter_name: str = parameter_name
self._message: str = message
super().__init__(message)
@property
def parameter_name(self) -> str:
return self._parameter_name
@property
def message(self) -> str:
return self._message
class AlreadyRegisteredError(Exception):
pass
class NotRegisteredError(Exception):
pass
class FunctionExecutingError(RuntimeError):
pass
class FunctionNotCancellableError(RuntimeError):
pass
class FunctionNotExecutingError(RuntimeError):
pass
class ParameterAlreadyExistError(RuntimeError):
def __init__(self, parameter_name: str):
self._parameter_name: str = parameter_name
def message(self) -> str:
return f"Parameter {self._parameter_name} already exists."
@property
def parameter_name(self) -> str:
return self._parameter_name
class ParameterNotFoundError(RuntimeError):
def __init__(self, parameter_name: str):
self._parameter_name: str = parameter_name
def message(self) -> str:
return f"Parameter {self._parameter_name} not found."
@property
def parameter_name(self) -> str:
return self._parameter_name
class ClipboardOperationError(RuntimeError):
def __init__(self, operation: int, message: str):
super().__init__(message)
self._operation: int = operation
@property
def operation(self) -> int:
return self._operation
| 1,691 | Python | .py | 51 | 27.54902 | 66 | 0.690194 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,462 | thread.py | zimolab_PyGUIAdapter/pyguiadapter/executors/thread.py | """
@Time : 2024.10.20
@File : thread.py
@Author : zimolab
@Project : PyGUIAdapter
@Desc : 实现了基于线程的函数执行器,是目前的默认实现。
"""
import threading
import traceback
from collections import OrderedDict
from typing import Any, Dict, Optional
from qtpy.QtCore import QObject, QThread, Signal
from ..exceptions import FunctionExecutingError
from ..executor import BaseFunctionExecutor, ExecuteStateListener
from ..fn import FnInfo
class _WorkerThread(QThread):
sig_result_ready = Signal(FnInfo, dict, object)
sig_error_raised = Signal(FnInfo, dict, Exception)
sig_cancel_requested = Signal()
# noinspection PyUnresolvedReferences
def __init__(
self,
parent: Optional[QObject],
fn_info: FnInfo,
arguments: Dict[str, Any],
):
super().__init__(parent)
self._fn_info = fn_info
self._arguments = OrderedDict(arguments)
self._cancel_event = threading.Event()
self.sig_cancel_requested.connect(self._on_cancel_requested)
def is_cancel_event_set(self) -> bool:
return self._cancel_event.is_set()
# noinspection PyUnresolvedReferences
def run(self):
try:
self._cancel_event.clear()
result = self._on_execute()
except Exception as e:
traceback.print_exc()
self.sig_error_raised.emit(self._fn_info, self._arguments, e)
else:
self.sig_result_ready.emit(self._fn_info, self._arguments, result)
finally:
self._cancel_event.clear()
def _on_execute(self) -> Any:
arguments = self._arguments.copy()
func = self._fn_info.fn
result = func(**arguments)
return result
def _on_cancel_requested(self):
self._cancel_event.set()
class ThreadFunctionExecutor(BaseFunctionExecutor):
def __init__(
self, parent: Optional[QObject], listener: Optional[ExecuteStateListener]
):
super().__init__(parent, listener)
self._worker_thread: Optional[_WorkerThread] = None
@property
def is_executing(self) -> bool:
return self._worker_thread is not None
@property
def is_cancelled(self) -> bool:
if not self.is_executing:
return False
return self._worker_thread.is_cancel_event_set()
# noinspection PyUnresolvedReferences
def execute(self, fn_info: FnInfo, arguments: Dict[str, Any]):
if self.is_executing:
raise FunctionExecutingError("function is executing")
def _callback_on_execute_start():
self._on_execute_start(fn_info, arguments)
def _callback_on_execute_finish():
self._on_execute_finish(fn_info, arguments)
self._reset_worker_thread()
self._before_execute(fn_info, arguments)
try:
self._worker_thread = _WorkerThread(self, fn_info, arguments)
self._worker_thread.started.connect(_callback_on_execute_start)
self._worker_thread.finished.connect(_callback_on_execute_finish)
self._worker_thread.sig_error_raised.connect(self._on_execute_error)
self._worker_thread.sig_result_ready.connect(self._on_execute_result)
self._worker_thread.start()
except Exception as e:
traceback.print_exc()
self._on_execute_error(fn_info, arguments, e)
self._on_execute_finish(fn_info, arguments)
def try_cancel(self):
if not self.is_executing:
return
if self.is_cancelled:
return
# noinspection PyUnresolvedReferences
self._worker_thread.sig_cancel_requested.emit()
def _before_execute(self, fn_info: FnInfo, arguments: Dict[str, Any]):
if self._listener:
self._listener.before_execute(fn_info, arguments)
def _on_execute_error(
self, fn_info: FnInfo, arguments: Dict[str, Any], error: Exception
):
if self._listener:
self._listener.on_execute_error(fn_info, arguments, error)
def _on_execute_start(self, fn_info: FnInfo, arguments: Dict[str, Any]):
if self._listener:
self._listener.on_execute_start(fn_info, arguments)
def _on_execute_finish(self, fn_info: FnInfo, arguments: Dict[str, Any]):
self._reset_worker_thread()
if self._listener:
self._listener.on_execute_finish(fn_info, arguments)
def _on_execute_result(
self, fn_info: FnInfo, arguments: Dict[str, Any], result: Any
):
if self._listener:
self._listener.on_execute_result(fn_info, arguments, result)
def _reset_worker_thread(self):
if self._worker_thread is not None:
self._worker_thread.setParent(None)
self._worker_thread.deleteLater()
self._worker_thread = None
| 4,868 | Python | .py | 119 | 32.386555 | 81 | 0.648053 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,463 | factory.py | zimolab_PyGUIAdapter/pyguiadapter/widgets/factory.py | import warnings
from typing import Dict, Type, List, Optional, Callable, Union
from .builtin import BUILTIN_WIDGETS_MAP, BUILTIN_WIDGETS_MAPPING_RULES
from ..exceptions import AlreadyRegisteredError
from ..fn import ParameterInfo
from ..paramwidget import (
BaseParameterWidget,
is_parameter_widget_class,
)
from ..parser import typenames
class ParameterWidgetRegistry(object):
def __init__(self):
self._registry: Dict[str, Type[BaseParameterWidget]] = {}
self.register_all(BUILTIN_WIDGETS_MAP)
def register(
self,
typ: Union[str, Type],
widget_class: Type[BaseParameterWidget],
replace: bool = False,
):
typ = self._to_typename(typ)
if not is_parameter_widget_class(widget_class):
raise TypeError(
f"widget_class is not a subclass of BaseParameterWidget: {widget_class}"
)
old_widget_class = self._registry.get(typ, None)
if old_widget_class is not None:
if not replace:
raise AlreadyRegisteredError(
f"typename has been registered already: {typ} -> {old_widget_class}"
)
else:
self._registry[typ] = widget_class
return
self._registry[typ] = widget_class
def register_all(self, mapping: Dict[Union[str, Type], Type[BaseParameterWidget]]):
for typename, widget_class in mapping.items():
self.register(typename, widget_class)
def unregister(self, typ: Union[str, Type]) -> Optional[Type[BaseParameterWidget]]:
return self._registry.pop(self._to_typename(typ), None)
def unregister_all(self, typs: List[Union[str, Type]]):
for typ in typs:
self.unregister(typ)
def is_registered(self, typ: Union[str, Type]) -> bool:
return self._to_typename(typ) in self._registry
def find_by_typename(
self, typ: Union[str, Type]
) -> Optional[Type[BaseParameterWidget]]:
return self._registry.get(self._to_typename(typ), None)
def find_by_widget_class_name(
self, widget_class_name: str
) -> Optional[Type[BaseParameterWidget]]:
return next(
(
widget_class
for widget_class in self._registry.values()
if widget_class.__name__ == widget_class_name
),
None,
)
@staticmethod
def _to_typename(typ: Union[str, Type]) -> str:
if isinstance(typ, str):
if typ.strip() == "":
raise ValueError(f"typename cannot be a empty string")
return typ
# elif isinstance(typ, type) or getattr(typ, "__name__", None) is not None:
# typename = typ.__name__
# if typename.strip() == "":
# raise ValueError(f"empty string")
# return typename
# else:
# raise TypeError(f"typ must be a type or typename: {typ}")
typename = typenames.get_typename(typ)
if typename is None or typename.strip():
raise ValueError(f"unable to get typename form: {typ}")
MappingRule = Callable[[ParameterInfo], Optional[Type[BaseParameterWidget]]]
class _ParameterWidgetFactory(ParameterWidgetRegistry):
def __init__(self):
super().__init__()
self._rules: List[MappingRule] = []
for rule in BUILTIN_WIDGETS_MAPPING_RULES:
self.add_mapping_rule(rule)
def find_by_rule(
self, parameter_info: ParameterInfo
) -> Optional[Type[BaseParameterWidget]]:
for rule in self._rules:
widget_class = self._do_mapping(rule, parameter_info)
if is_parameter_widget_class(widget_class):
return widget_class
return None
def has_mapping_rule(self, rule: MappingRule) -> bool:
return rule in self._rules
def add_mapping_rule(self, rule: MappingRule):
if rule not in self._rules:
self._rules.append(rule)
def remove_mapping_rule(self, rule: MappingRule):
if rule in self._rules:
self._rules.remove(rule)
def clear_mapping_rules(self):
self._rules.clear()
@staticmethod
def _do_mapping(
rule: MappingRule, parameter_info: ParameterInfo
) -> Optional[Type[BaseParameterWidget]]:
try:
return rule(parameter_info)
except Exception as e:
warnings.warn(f"failed to apply mapping rule '{rule.__name__}': {e}")
return None
ParameterWidgetFactory = _ParameterWidgetFactory()
| 4,589 | Python | .py | 111 | 32.36036 | 88 | 0.621743 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,464 | __init__.py | zimolab_PyGUIAdapter/pyguiadapter/widgets/__init__.py | from .basic import *
from .extend import *
from .common import CommonParameterWidgetConfig, CommonParameterWidget
from .factory import ParameterWidgetFactory
| 158 | Python | .py | 4 | 38.5 | 70 | 0.87013 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,465 | builtin.py | zimolab_PyGUIAdapter/pyguiadapter/widgets/builtin.py | from datetime import datetime, date, time
from qtpy.QtGui import QColor
from .basic import (
PyLiteralEdit,
PyLiteralType,
DictEdit,
ListEdit,
TupleEdit,
SetEdit,
LineEdit,
IntSpinBox,
FloatSpinBox,
BoolBox,
EnumSelect,
ExclusiveChoiceBox,
DateTimeEdit,
DateEdit,
TimeEdit,
)
from .extend import (
IntLineEdit,
FloatLineEdit,
JsonEdit,
TextEdit,
ChoiceBox,
MultiChoiceBox,
Slider,
Dial,
ColorTuplePicker,
ColorHexPicker,
ColorPicker,
KeySequenceEdit,
StringListEdit,
PlainDictEdit,
DirSelect,
FileSelect,
MultiFileSelect,
)
from ..parser.typenames import (
TYPE_STR,
TYPE_INT,
TYPE_FLOAT,
TYPE_ANY,
TYPE_OBJECT,
TYPE_DICT,
TYPE_LIST,
TYPE_TUPLE,
TYPE_SET,
TYPE_BOOL,
TYPING_ANY,
TYPING_LITERAL,
TYPING_UNION,
TYPING_DICT,
TYPING_LIST,
TYPING_TUPLE,
TYPING_SET,
TYPE_MAPPING,
TYPE_MUTABLE_MAPPING,
TYPE_MUTABLE_SET,
TYPING_TYPED_DICT,
)
from ..extend_types import (
text_t,
int_t,
float_t,
directory_t,
file_t,
files_t,
json_obj_t,
choice_t,
choices_t,
int_slider_t,
int_dial_t,
color_tuple_t,
color_hex_t,
key_sequence_t,
string_list_t,
plain_dict_t,
color_t,
)
TYPE_TEXT = text_t.__name__
TYPE_INT_T = int_t.__name__
TYPE_FLOAT_T = float_t.__name__
TYPE_DIR_T = directory_t.__name__
TYPE_FILE_T = file_t.__name__
TYPE_FILES_T = files_t.__name__
TYPE_JSON_OBJ_T = json_obj_t.__name__
TYPE_PY_LITERAL = str(PyLiteralType)
TYPE_CHOICE_T = choice_t.__name__
TYPE_CHOICES_T = choices_t.__name__
TYPE_SLIDER_INT_T = int_slider_t.__name__
TYPE_DIAL_INT_T = int_dial_t.__name__
TYPE_DATETIME = datetime.__name__
TYPE_DATE = date.__name__
TYPE_TIME = time.__name__
TYPE_COLOR_TUPLE = color_tuple_t.__name__
TYPE_COLOR_HEX = color_hex_t.__name__
# noinspection SpellCheckingInspection
TYPE_QCOLOR = QColor.__name__
TYPE_COLOR_T = color_t.__name__
TYPE_KEY_SEQUENCE_T = key_sequence_t.__name__
TYPE_STRING_LIST_T = string_list_t.__name__
TYPE_PLAIN_DICT_T = plain_dict_t.__name__
BUILTIN_WIDGETS_MAP = {
TYPE_STR: LineEdit,
TYPE_TEXT: TextEdit,
TYPE_INT: IntSpinBox,
TYPE_BOOL: BoolBox,
TYPE_INT_T: IntLineEdit,
TYPE_FLOAT: FloatSpinBox,
TYPE_FLOAT_T: FloatLineEdit,
TYPE_DIR_T: DirSelect,
TYPE_FILE_T: FileSelect,
TYPE_FILES_T: MultiFileSelect,
TYPE_JSON_OBJ_T: JsonEdit,
TYPE_ANY: PyLiteralEdit,
TYPING_ANY: PyLiteralEdit,
TYPE_PY_LITERAL: PyLiteralEdit,
TYPING_UNION: PyLiteralEdit,
TYPE_OBJECT: PyLiteralEdit,
TYPE_DICT: DictEdit,
TYPING_DICT: DictEdit,
TYPE_MAPPING: DictEdit,
TYPE_MUTABLE_MAPPING: DictEdit,
TYPING_TYPED_DICT: DictEdit,
TYPE_LIST: ListEdit,
TYPING_LIST: ListEdit,
TYPE_TUPLE: TupleEdit,
TYPING_TUPLE: TupleEdit,
TYPE_SET: SetEdit,
TYPING_SET: SetEdit,
TYPE_MUTABLE_SET: SetEdit,
TYPING_LITERAL: ExclusiveChoiceBox,
TYPE_CHOICE_T: ChoiceBox,
TYPE_CHOICES_T: MultiChoiceBox,
TYPE_SLIDER_INT_T: Slider,
TYPE_DIAL_INT_T: Dial,
TYPE_DATETIME: DateTimeEdit,
TYPE_DATE: DateEdit,
TYPE_TIME: TimeEdit,
TYPE_COLOR_TUPLE: ColorTuplePicker,
TYPE_COLOR_HEX: ColorHexPicker,
TYPE_QCOLOR: ColorPicker,
TYPE_COLOR_T: ColorPicker,
TYPE_KEY_SEQUENCE_T: KeySequenceEdit,
TYPE_STRING_LIST_T: StringListEdit,
TYPE_PLAIN_DICT_T: PlainDictEdit,
}
# noinspection PyProtectedMember
BUILTIN_WIDGETS_MAPPING_RULES = [
EnumSelect._enum_type_mapping_rule,
DictEdit._dict_mapping_rule,
]
| 3,638 | Python | .py | 153 | 19.732026 | 45 | 0.686404 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,466 | common.py | zimolab_PyGUIAdapter/pyguiadapter/widgets/common.py | import copy
import dataclasses
from abc import abstractmethod
from typing import Any, Type, Optional, Tuple, Sequence
from qtpy.QtCore import Qt, QPropertyAnimation, QEasingCurve, QMimeData, QUrl
from qtpy.QtGui import QDragEnterEvent, QDropEvent
from qtpy.QtGui import QColor
from qtpy.QtWidgets import (
QWidget,
QVBoxLayout,
QGroupBox,
QLabel,
QCheckBox,
QSpacerItem,
QSizePolicy,
QGraphicsEffect,
QGraphicsDropShadowEffect,
)
from ..constants.color import COLOR_FATAL, COLOR_REGULAR_TEXT
from ..constants.font import FONT_SMALL
from ..exceptions import ParameterError
from ..paramwidget import BaseParameterWidgetConfig, BaseParameterWidget
DEFAULT_HIGHLIGHT_EFFECT_PROPERTIES = {
"BlurRadius": 10,
"Color": QColor("#ff0000"),
"XOffset": 0.3,
"YOffset": 0.3,
"Enabled": False,
}
def _default_highlight_effect_properties() -> dict:
return DEFAULT_HIGHLIGHT_EFFECT_PROPERTIES
@dataclasses.dataclass(frozen=True)
class CommonParameterWidgetConfig(BaseParameterWidgetConfig):
"""
通用参数控件配置类。继承自 `BaseParameterWidgetConfig` 类。是所有通用参数控件的配置基类。
"""
set_default_value_on_init: bool = True
"""
是否在控件初始化时设置默认值。默认为 `True`。
"""
hide_default_value_checkbox: bool = True
"""是否隐藏默认值复选框。当default_value为None时,此选项无效,默认值复选框始终显示。"""
set_deepcopy: bool = True
get_deepcopy: bool = True
description_font_size: Optional[int] = FONT_SMALL
"""控件描述文本字体大小。默认为 `FONT_SMALL`。"""
description_color: Optional[str] = COLOR_REGULAR_TEXT
"""控件描述文本颜色。默认为 `COLOR_REGULAR_TEXT`。"""
parameter_error_font_size: Optional[int] = FONT_SMALL
"""ParameterError文本字体大小。默认为 `FONT_SMALL`。"""
parameter_error_color: Optional[str] = COLOR_FATAL
"""ParameterError文本颜色。默认为 `COLOR_FATAL`。"""
highlight_effect: bool = True
"""是否启用高亮效果。当启用高亮效果时,允许开发者高亮显示该控件。"""
effect_class: Optional[Type[QGraphicsEffect]] = QGraphicsDropShadowEffect
"""高亮效果类。默认为 `QGraphicsDropShadowEffect`。"""
effect_properties: Optional[dict] = dataclasses.field(
default_factory=_default_highlight_effect_properties
)
"""高亮效果属性。默认为 `None`。"""
drag_n_drop: bool = False
"""是否启用拖放功能。默认为 `False`。"""
@classmethod
def target_widget_class(cls) -> Type["CommonParameterWidget"]:
return CommonParameterWidget
class CommonParameterWidget(BaseParameterWidget):
"""
通用参数控件基类。继承自 `BaseParameterWidget` 类。为所有参数控件定义了基本的布局和整体外观。目前内置控件均继承自此类。
"""
ConfigClass: Type[CommonParameterWidgetConfig] = NotImplemented
def __init__(
self,
parent: Optional[QWidget],
parameter_name: str,
config: CommonParameterWidgetConfig,
):
self._config: CommonParameterWidgetConfig = config
super().__init__(parent, parameter_name, config)
self._layout_main = QVBoxLayout()
self._layout_main.setContentsMargins(0, 0, 0, 0)
self._layout_main.setSpacing(0)
self.setLayout(self._layout_main)
self._groupbox_outline = QGroupBox(self)
self._groupbox_outline.setTitle(self.label)
self._layout_container = QVBoxLayout()
self._groupbox_outline.setLayout(self._layout_container)
self._layout_main.addWidget(self._groupbox_outline)
self._label_description: Optional[QLabel] = None
self._checkbox_default_value: Optional[QCheckBox] = None
self._label_parameter_error: Optional[QLabel] = None
self._highlight_animation: Optional[QPropertyAnimation] = None
self._highlight_effect: Optional[QGraphicsEffect] = None
if self._config.highlight_effect:
self._highlight_effect = self._create_highlight_effect()
self._highlight_animation = QPropertyAnimation(
self._highlight_effect, b"blurRadius"
)
self._highlight_animation.setParent(self)
# noinspection PyUnresolvedReferences
self._highlight_animation.finished.connect(
self._on_highlight_effect_finished
)
self.__build_flag: bool = False
def build(self):
if self.__build_flag:
return self
if self._highlight_effect:
self.setGraphicsEffect(self._highlight_effect)
if self.config.drag_n_drop:
self._enable_drag_n_drop()
if self.description:
self._layout_container.addWidget(self.description_label)
self._layout_container.addWidget(self.value_widget)
self._layout_container.addWidget(self.default_value_checkbox)
self._layout_container.addWidget(self.parameter_error_label)
self._layout_container.addSpacerItem(
QSpacerItem(
0, 0, QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Expanding
)
)
self.__build_flag = True
return self
def check_value_type(self, value: Any):
pass
def set_value(self, value: Any):
try:
self.check_value_type(value)
if self._config.set_deepcopy:
value = copy.deepcopy(value)
if not self._check_set_value(value):
return
self.set_value_to_widget(value)
except (TypeError, ValueError) as e:
raise ParameterError(parameter_name=self.parameter_name, message=str(e))
def get_value(self) -> Any:
if self._default_value_used():
return self.default_value
try:
original_value = self.get_value_from_widget()
except (ValueError, TypeError) as e:
raise ParameterError(parameter_name=self.parameter_name, message=str(e))
else:
if self._config.get_deepcopy:
return copy.deepcopy(original_value)
return original_value
@property
def label(self) -> str:
return super().label
@label.setter
def label(self, value: str):
if self.label == value:
return
self._groupbox_outline.setTitle(value)
# noinspection PyUnresolvedReferences
super(CommonParameterWidget, CommonParameterWidget).label.__set__(self, value)
@property
def description(self) -> str:
return super().description
@description.setter
def description(self, value: str):
if self.description == value:
return
self.description_label.setText(value)
# noinspection PyUnresolvedReferences
super(CommonParameterWidget, CommonParameterWidget).description.__set__(
self, value
)
@property
def default_value_description(self) -> str:
return super().default_value_description
@default_value_description.setter
def default_value_description(self, value: str):
if self.default_value_description == value:
return
self.default_value_checkbox.setText(value.format(str(self.default_value)))
# noinspection PyUnresolvedReferences
super(
CommonParameterWidget, CommonParameterWidget
).default_value_description.__set__(self, value)
@property
def hide_default_value_checkbox(self) -> bool:
if self.default_value is None:
return False
return self._config.hide_default_value_checkbox
@property
def set_default_value_on_init(self) -> bool:
if self.default_value is not None and self.hide_default_value_checkbox:
return True
return self._config.set_default_value_on_init
@property
@abstractmethod
def value_widget(self) -> QWidget:
"""
返回“值控件”。此为抽象方法,必须在子类中实现。
Returns:
控件示例。
"""
pass
@property
def description_label(self) -> QLabel:
if self._label_description is not None:
return self._label_description
self._label_description = QLabel(self._groupbox_outline)
self._label_description.setWordWrap(True)
self._label_description.setAlignment(
Qt.AlignLeading | Qt.AlignLeft | Qt.AlignTop
)
self._label_description.setIndent(-1)
self._label_description.setOpenExternalLinks(True)
if self._config.description_color:
self._label_description.setStyleSheet(
f'color: "{self._config.description_color}"'
)
if self._config.description_font_size:
font = self._label_description.font()
font.setPixelSize(self._config.description_font_size)
self._label_description.setFont(font)
if self.description:
self._label_description.setText(self.description)
return self._label_description
@property
def default_value_checkbox(self) -> QCheckBox:
if self._checkbox_default_value is not None:
return self._checkbox_default_value
self._checkbox_default_value = QCheckBox(self._groupbox_outline)
self._checkbox_default_value.setText(
self.default_value_description.format(str(self.default_value))
)
def _on_toggled(checked: bool):
if self.hide_default_value_checkbox:
return
self.value_widget.setEnabled(not checked)
# noinspection PyUnresolvedReferences
self._checkbox_default_value.toggled.connect(_on_toggled)
if self.hide_default_value_checkbox:
self._checkbox_default_value.setHidden(True)
return self._checkbox_default_value
@property
def parameter_error_label(self) -> QLabel:
if self._label_parameter_error is not None:
return self._label_parameter_error
self._label_parameter_error = QLabel(self._groupbox_outline)
self._label_parameter_error.setWordWrap(True)
self._label_parameter_error.setAlignment(
Qt.AlignLeading | Qt.AlignLeft | Qt.AlignTop
)
if self._config.parameter_error_color:
self._label_parameter_error.setStyleSheet(
f'color: "{self._config.parameter_error_color}"'
)
if self._config.parameter_error_font_size:
font = self._label_parameter_error.font()
font.setPixelSize(self._config.parameter_error_font_size)
self._label_parameter_error.setFont(font)
self._label_parameter_error.setIndent(-1)
self._label_parameter_error.setOpenExternalLinks(True)
self._label_parameter_error.setHidden(True)
return self._label_parameter_error
def show_parameter_error(self, error: str):
self.parameter_error_label.setText(error)
self.parameter_error_label.setHidden(False)
def clear_parameter_error(self):
self.parameter_error_label.setText("")
self.parameter_error_label.setHidden(True)
@abstractmethod
def set_value_to_widget(self, value: Any) -> None:
"""
将用户传入的值设置到“值控件”中。此为抽象方法,必须在子类中实现。
Args:
value: 用户传入的值
Returns:
无返回值
"""
pass
@abstractmethod
def get_value_from_widget(self) -> Any:
"""
从“值控件”中获取用户当前输入的值。此为抽象方法,必须在子类中实现。
Returns:
用户当前输入的值
"""
pass
def on_parameter_error(self, parameter_name: str, error: Any):
if parameter_name != self.parameter_name:
return
error_message = str(error)
self.show_parameter_error(error_message)
def on_clear_parameter_error(self, parameter_name: Optional[str]):
if parameter_name is None or parameter_name == self.parameter_name:
self.clear_parameter_error()
def play_highlight_effect(
self,
duration: int = 500,
start_value: float = 10.0,
end_value: float = 5,
key_values: Optional[Sequence[Tuple[float, Any]]] = ((0.5, 0.5),),
easing_curve: QEasingCurve = QEasingCurve.InOutBounce,
):
if not self._highlight_effect:
return
if not self._highlight_animation:
return
self._highlight_effect.setEnabled(True)
self._highlight_animation.stop()
self._highlight_animation.setDuration(duration)
self._highlight_animation.setStartValue(start_value)
self._highlight_animation.setEndValue(end_value)
if key_values:
for key_time, key_value in key_values:
self._highlight_animation.setKeyValueAt(key_time, key_value)
self._highlight_animation.setEasingCurve(easing_curve)
self._highlight_animation.start()
def dragEnterEvent(self, event: QDragEnterEvent):
if not self._config.drag_n_drop:
event.ignore()
return
accepted = self.on_drag(event.mimeData())
if accepted:
event.acceptProposedAction()
else:
event.ignore()
def dropEvent(self, event: QDropEvent):
if not self._config.drag_n_drop:
event.ignore()
return
mime_data = event.mimeData()
urls = mime_data.urls()
event.acceptProposedAction()
self.on_drop(urls, mime_data)
def on_drag(self, mime_data: QMimeData) -> bool:
pass
def on_drop(self, urls: Sequence[QUrl], mime_data: QMimeData):
pass
def _enable_drag_n_drop(self):
self.setAcceptDrops(True)
def _create_highlight_effect(self) -> Optional[QGraphicsEffect]:
## MAKE SURE THIS METHOD MUST BE CALLED ONCE
if not self._config.highlight_effect:
return None
effect = QGraphicsDropShadowEffect(self)
properties = self._config.effect_properties or {}
for prop_name, prop_value in properties.items():
prop_name = "set" + prop_name
setter = getattr(effect, prop_name, None)
if setter is not None and callable(setter):
setter(prop_value)
else:
raise ValueError(f"invalid highlight effect property: {prop_name}")
return effect
def _on_highlight_effect_finished(self):
self._highlight_effect.setEnabled(False)
def _default_value_used(self) -> bool:
if self.default_value_checkbox.isHidden():
return False
return self._checkbox_default_value.isChecked()
def _use_default_value(self):
if self.hide_default_value_checkbox or self.default_value_checkbox.isHidden():
return
self.default_value_checkbox.setChecked(True)
# noinspection SpellCheckingInspection
def _unuse_default_value(self):
if self.hide_default_value_checkbox or self.default_value_checkbox.isHidden():
return
self.default_value_checkbox.setChecked(False)
def _check_set_value(self, value: Any) -> bool:
if value is None and self.default_value is not None:
raise ValueError(
f"None value is not allowed unless the default_value is None(default_value={self.default_value})"
)
if value is None and self.default_value is None:
self._use_default_value()
return False
if value == self.default_value:
self._use_default_value()
else:
self._unuse_default_value()
return True
| 15,967 | Python | .py | 377 | 31.625995 | 113 | 0.653017 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,467 | dictedit.py | zimolab_PyGUIAdapter/pyguiadapter/widgets/basic/dictedit.py | import dataclasses
from qtpy.QtWidgets import QWidget
from typing import Type, Optional, Any
from .base import StandaloneCodeEditorConfig
from .pyliteraledit import PyLiteralEdit, PyLiteralEditConfig, PyLiteralType
from ... import utils
from ...fn import ParameterInfo
from ...utils import type_check
@dataclasses.dataclass(frozen=True)
class DictEditConfig(PyLiteralEditConfig):
"""DictEdit的配置类"""
default_value: Optional[dict] = dataclasses.field(default_factory=dict)
"""控件的默认值"""
height: Optional[int] = None
"""inplace编辑器的高度"""
width: Optional[int] = None
"""inplace编辑器的宽度"""
standalone_editor: bool = True
"""是否启用独立(standalone)代码编辑器"""
standalone_editor_button: bool = "Edit Dict"
"""standalone编辑器启动按钮文本"""
standalone_editor_config: StandaloneCodeEditorConfig = dataclasses.field(
default_factory=StandaloneCodeEditorConfig
)
"""standalone编辑器配置"""
initial_text: str = "{}"
@classmethod
def target_widget_class(cls) -> Type["DictEdit"]:
return DictEdit
class DictEdit(PyLiteralEdit):
ConfigClass = DictEditConfig
def __init__(
self, parent: Optional[QWidget], parameter_name: str, config: DictEditConfig
):
super().__init__(parent, parameter_name, config)
def _get_data(self, text: str) -> Optional[dict]:
if text is None or text.strip() == "":
return None
data = super()._get_data(text)
if data is None:
return None
if not isinstance(data, dict):
raise ValueError(f"not a dict")
return data
def check_value_type(self, value: Any):
type_check(value, (dict,), allow_none=True)
def _set_data(self, data: PyLiteralType) -> str:
if data is None:
return "None"
if isinstance(data, str) and data.strip() == "":
return "None"
if not isinstance(data, dict):
raise ValueError(f"not a dict: {data}")
return super()._set_data(data)
@classmethod
def _dict_mapping_rule(
cls, parameter_info: ParameterInfo
) -> Optional[Type["DictEdit"]]:
return DictEdit if utils.is_subclass_of(parameter_info.type, dict) else None
| 2,329 | Python | .py | 59 | 31.338983 | 84 | 0.668834 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,468 | boolbox.py | zimolab_PyGUIAdapter/pyguiadapter/widgets/basic/boolbox.py | import dataclasses
from qtpy.QtWidgets import QWidget, QButtonGroup, QRadioButton, QVBoxLayout, QHBoxLayout
from typing import Type, Optional, Any
from ..common import CommonParameterWidgetConfig, CommonParameterWidget
from ...utils import IconType, get_icon, type_check
@dataclasses.dataclass(frozen=True)
class BoolBoxConfig(CommonParameterWidgetConfig):
"""
BoolBox控件的配置类。
"""
default_value: Optional[bool] = False
"""控件的默认值。"""
true_text: str = "True"
"""值为True的选项文本"""
false_text: str = "False"
"""值为False的选项文本"""
true_icon: IconType = None
"""值为True的选项图标"""
false_icon: IconType = None
"""值为False的选项图标"""
vertical: bool = False
"""是否为垂直布局"""
@classmethod
def target_widget_class(cls) -> Type["BoolBox"]:
return BoolBox
class BoolBox(CommonParameterWidget):
ConfigClass: Type[BoolBoxConfig] = BoolBoxConfig
def __init__(
self,
parent: Optional[QWidget],
parameter_name: str,
config: BoolBoxConfig,
):
self._value_widget: Optional[QWidget] = None
self._true_radio_button: Optional[QRadioButton] = None
self._false_radio_button: Optional[QRadioButton] = None
self._button_group: Optional[QButtonGroup] = None
super().__init__(parent, parameter_name, config)
@property
def value_widget(self) -> QWidget:
if self._value_widget is None:
config: BoolBoxConfig = self.config
self._value_widget = QWidget(self)
if config.vertical:
layout = QVBoxLayout()
else:
layout = QHBoxLayout()
self._value_widget.setLayout(layout)
self._true_radio_button = QRadioButton(self._value_widget)
self._true_radio_button.setText(config.true_text)
true_icon = get_icon(config.true_icon)
if true_icon is not None:
self._true_radio_button.setIcon(true_icon)
self._false_radio_button = QRadioButton(self._value_widget)
self._false_radio_button.setText(config.false_text)
false_icon = get_icon(config.false_icon)
if false_icon is not None:
self._false_radio_button.setIcon(false_icon)
self._button_group = QButtonGroup(self._value_widget)
self._button_group.addButton(self._true_radio_button)
self._button_group.addButton(self._false_radio_button)
self._button_group.setExclusive(True)
layout.addWidget(self._true_radio_button)
layout.addWidget(self._false_radio_button)
return self._value_widget
def check_value_type(self, value: Any):
type_check(value, (bool, int), allow_none=True)
def set_value_to_widget(self, value: bool):
if value:
self._true_radio_button.setChecked(True)
else:
self._false_radio_button.setChecked(True)
def get_value_from_widget(self) -> bool:
return self._true_radio_button.isChecked()
| 3,153 | Python | .py | 74 | 32.594595 | 88 | 0.646482 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,469 | enumselect.py | zimolab_PyGUIAdapter/pyguiadapter/widgets/basic/enumselect.py | import dataclasses
import inspect
from enum import Enum
from qtpy.QtCore import QSize
from qtpy.QtWidgets import QWidget, QComboBox
from typing import Type, Tuple, Union, Optional, Dict, Any
from ..common import CommonParameterWidgetConfig, CommonParameterWidget
from ...fn import ParameterInfo
from ...utils import IconType, get_icon, get_size, is_subclass_of, type_check
@dataclasses.dataclass(frozen=True)
class EnumSelectConfig(CommonParameterWidgetConfig):
"""EnumSelect的配置类"""
default_value: Union[Enum, str, int, None] = 0
"""默认的枚举值,可以为枚举类对象、枚举对象的名称或者是选项的索引"""
icons: Optional[Dict[Union[Enum, str], IconType]] = None
"""选项的图标,需提供枚举对象(或枚举对象的名称)到图标的映射"""
icon_size: Union[int, Tuple[int, int], QSize, None] = None
"""选项图标的大小"""
enum_class: Optional[Type[Enum]] = None
@classmethod
def target_widget_class(cls) -> Type["EnumSelect"]:
return EnumSelect
class EnumSelect(CommonParameterWidget):
ConfigClass = EnumSelectConfig
def __init__(
self,
parent: Optional[QWidget],
parameter_name: str,
config: EnumSelectConfig,
):
self._value_widget: Optional[QComboBox] = None
super().__init__(parent, parameter_name, config)
@property
def value_widget(self) -> QComboBox:
if self._value_widget is None:
config: EnumSelectConfig = self.config
self._value_widget = QComboBox(self)
icon_size = get_size(config.icon_size)
if icon_size:
self._value_widget.setIconSize(icon_size)
all_enums = config.enum_class.__members__
for enum_name, enum_value in all_enums.items():
self._add_item(enum_name, enum_value, config.icons)
return self._value_widget
def _add_item(
self,
name: str,
value: Enum,
icons: Optional[Dict[Union[Enum, str], IconType]],
):
if not icons:
self._value_widget.addItem(name, value)
return
icon = icons.get(name, None)
if not icon:
icon = icons.get(value, None)
if not icon:
self._value_widget.addItem(name, value)
return
icon = get_icon(icon)
if icon:
self._value_widget.addItem(icon, name, value)
return
self._value_widget.addItem(name, value)
def check_value_type(self, value: Any):
self._config: EnumSelectConfig
type_check(value, (str, int, self._config.enum_class), allow_none=True)
def set_value_to_widget(self, value: Union[Enum, str, int]):
if isinstance(value, int):
if value < 0 or value >= self._value_widget.count():
raise ValueError(f"invalid index: {value}")
self._value_widget.setCurrentIndex(value)
return
if isinstance(value, Enum):
self._value_widget.setCurrentText(value.name)
return
if isinstance(value, str):
self._config: EnumSelectConfig
if value not in self._config.enum_class.__members__:
raise ValueError(f"invalid enum name: {value}")
self._value_widget.setCurrentText(value)
return
def get_value_from_widget(self) -> Enum:
return self._value_widget.currentData()
@classmethod
def on_post_process_config(
cls,
config: EnumSelectConfig,
parameter_name: str,
parameter_info: ParameterInfo,
) -> EnumSelectConfig:
if inspect.isclass(config.enum_class) and issubclass(config.enum_class, Enum):
return config
assert inspect.isclass(parameter_info.type) and issubclass(
parameter_info.type, Enum
)
return dataclasses.replace(config, enum_class=parameter_info.type)
@classmethod
def _enum_type_mapping_rule(
cls, parameter_info: ParameterInfo
) -> Optional[Type["EnumSelect"]]:
if is_subclass_of(parameter_info.type, Enum):
return cls
return None
| 4,205 | Python | .py | 104 | 30.509615 | 86 | 0.636779 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,470 | exclusivechoice.py | zimolab_PyGUIAdapter/pyguiadapter/widgets/basic/exclusivechoice.py | import dataclasses
from typing import Type, List, Any, Tuple, Optional, Union
from qtpy.QtCore import QSize
from qtpy.QtGui import QIcon
from qtpy.QtWidgets import QWidget, QGridLayout, QRadioButton, QButtonGroup
from ..common import CommonParameterWidgetConfig, CommonParameterWidget
from ...utils import IconType, get_icon, unique_list, get_size
from ...fn import ParameterInfo
class _ChoiceButton(QRadioButton):
def __init__(self, parent: Optional[QWidget], user_data: Any):
super().__init__(parent)
self._user_data = user_data
@property
def user_data(self) -> Any:
return self._user_data
# noinspection PyPep8Naming
class _FIRST_OPTION:
__slots__ = ()
@dataclasses.dataclass(frozen=True)
class ExclusiveChoiceBoxConfig(CommonParameterWidgetConfig):
"""ExclusiveChoiceBox的配置类。"""
default_value: Any = _FIRST_OPTION
"""默认选项。`_FIRST_OPTION`是一个特殊值,表示选择选项列表中的第一个选项。"""
choices: Optional[List[Any]] = None
"""选项列表"""
columns: int = 1
"""选项列数"""
show_type_icon: bool = False
"""是否显示选项类型图标"""
int_icon: IconType = "mdi6.alpha-i-circle"
"""整数类型选项的图标"""
bool_icon: str = "mdi6.alpha-b-circle"
"""布尔类型选项的图标"""
str_icon: str = "mdi6.alpha-s-box"
"""字符串类型选项的图标"""
object_icon: str_icon = "mdi6.alpha-o-box"
"""对象类型选项的图标"""
icon_size: Union[Tuple[int, int], int, QSize, None] = None
"""选项图标大小"""
@classmethod
def target_widget_class(cls) -> Type["ExclusiveChoiceBox"]:
return ExclusiveChoiceBox
class ExclusiveChoiceBox(CommonParameterWidget):
ConfigClass = ExclusiveChoiceBoxConfig
def __init__(
self,
parent: Optional[QWidget],
parameter_name: str,
config: ExclusiveChoiceBoxConfig,
):
self._value_widget: Optional[QWidget] = None
self._button_group: Optional[QButtonGroup] = None
self._button_layout: Optional[QGridLayout] = None
super().__init__(parent, parameter_name, config)
@property
def value_widget(self) -> QWidget:
self._config: ExclusiveChoiceBoxConfig
if self._value_widget is None:
self._value_widget = QWidget(self)
self._button_layout = QGridLayout()
self._value_widget.setLayout(self._button_layout)
self._button_group = QButtonGroup(self._value_widget)
self._button_group.setExclusive(True)
self._add_choices()
return self._value_widget
def set_value_to_widget(self, value: Any):
if value is _FIRST_OPTION:
self._button_group.buttons()[0].setChecked(True)
return
for btn in self._button_group.buttons():
assert isinstance(btn, _ChoiceButton)
user_data = btn.user_data
if user_data == value:
btn.setChecked(True)
break
def get_value_from_widget(self) -> Any:
for btn in self._button_group.buttons():
assert isinstance(btn, _ChoiceButton)
if btn.isChecked():
return btn.user_data
return None
def _add_choices(self):
self._config: ExclusiveChoiceBoxConfig
choices = unique_list(self._config.choices)
cols = max(self._config.columns, 1)
for idx, choice in enumerate(choices):
btn = _ChoiceButton(self._value_widget, choice)
icon_size = get_size(self._config.icon_size)
if icon_size is not None:
btn.setIconSize(icon_size)
btn.setText(str(choice))
if self._config.show_type_icon:
str_icon = get_icon(self._config.str_icon) or QIcon()
bool_icon = get_icon(self._config.bool_icon) or QIcon()
int_icon = get_icon(self._config.int_icon) or QIcon()
object_icon = get_icon(self._config.object_icon) or QIcon()
if isinstance(choice, str):
btn.setIcon(str_icon)
elif isinstance(choice, bool):
btn.setIcon(bool_icon)
elif isinstance(choice, int):
btn.setIcon(int_icon)
else:
btn.setIcon(object_icon)
self._button_group.addButton(btn)
if idx % cols == 0:
self._button_layout.addWidget(btn, idx // cols, 0)
else:
self._button_layout.addWidget(btn, idx // cols, idx % cols)
@classmethod
def on_post_process_config(
cls,
config: ExclusiveChoiceBoxConfig,
parameter_name: str,
parameter_info: ParameterInfo,
) -> ExclusiveChoiceBoxConfig:
if not config.choices and len(parameter_info.type_args) > 0:
config = dataclasses.replace(
config, choices=parameter_info.type_args.copy()
)
return config
| 5,071 | Python | .py | 121 | 31.099174 | 75 | 0.619007 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,471 | listedit.py | zimolab_PyGUIAdapter/pyguiadapter/widgets/basic/listedit.py | import dataclasses
from qtpy.QtWidgets import QWidget
from typing import Type, Optional, Any
from .base import StandaloneCodeEditorConfig
from .pyliteraledit import PyLiteralEdit, PyLiteralEditConfig, PyLiteralType
from ...utils import type_check
@dataclasses.dataclass(frozen=True)
class ListEditConfig(PyLiteralEditConfig):
"""ListEdit的配置类"""
default_value: Optional[list] = dataclasses.field(default_factory=list)
"""控件的默认值"""
height: Optional[int] = None
"""inplace编辑器的高度"""
width: Optional[int] = None
"""inplace编辑器的宽度"""
standalone_editor: bool = True
"""是否启用独立(standalone)代码编辑器"""
standalone_editor_button: bool = "Edit List"
"""standalone编辑器启动按钮文本"""
standalone_editor_config: StandaloneCodeEditorConfig = dataclasses.field(
default_factory=StandaloneCodeEditorConfig
)
"""standalone编辑器配置"""
initial_text: str = "[]"
@classmethod
def target_widget_class(cls) -> Type["ListEdit"]:
return ListEdit
class ListEdit(PyLiteralEdit):
ConfigClass = ListEditConfig
def __init__(
self, parent: Optional[QWidget], parameter_name: str, config: ListEditConfig
):
super().__init__(parent, parameter_name, config)
def check_value_type(self, value: Any):
if value == "":
return
type_check(value, (list,), allow_none=True)
def _get_data(self, text: str) -> Optional[list]:
text = text.strip()
if text is None or text == "":
return None
data = super()._get_data(text)
if data is None:
return None
if not isinstance(data, list):
raise ValueError(f"not a list")
return data
def _set_data(self, data: PyLiteralType) -> str:
if data is None:
return "None"
if isinstance(data, str) and data.strip() == "":
return "None"
if not isinstance(data, list):
raise ValueError(f"not a list: {data}")
return super()._set_data(data)
| 2,127 | Python | .py | 55 | 30.036364 | 84 | 0.654908 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,472 | pyliteraledit.py | zimolab_PyGUIAdapter/pyguiadapter/widgets/basic/pyliteraledit.py | import ast
import dataclasses
from pyqcodeeditor.highlighters import QPythonHighlighter
from qtpy.QtWidgets import QWidget
from typing import Type, Optional, Any
from .base import BaseCodeEdit, BaseCodeEditConfig, StandaloneCodeEditorConfig
from ...codeeditor import PythonFormatter
from ...utils import PyLiteralType, type_check
@dataclasses.dataclass(frozen=True)
class PyLiteralEditConfig(BaseCodeEditConfig):
"""PyLiteralEdit的配置类"""
default_value: PyLiteralType = ""
"""控件的默认值"""
height: Optional[int] = None
"""inplace编辑器的高度"""
width: Optional[int] = None
"""inplace编辑器的宽度"""
standalone_editor: bool = True
"""是否使用独立(standalone)编辑器窗口"""
standalone_editor_button: str = "Edit Python Literal"
"""standalone编辑器窗口打开按钮的文本"""
standalone_editor_config: StandaloneCodeEditorConfig = dataclasses.field(
default_factory=StandaloneCodeEditorConfig
)
"""standalone编辑器配置"""
initial_text: str = ""
# DON'T CHANGE THE VALUES BELOW
highlighter: Type[QPythonHighlighter] = QPythonHighlighter
formatter: QPythonHighlighter = PythonFormatter()
@classmethod
def target_widget_class(cls) -> Type["PyLiteralEdit"]:
return PyLiteralEdit
class PyLiteralEdit(BaseCodeEdit):
ConfigClass = PyLiteralEditConfig
def __init__(
self,
parent: Optional[QWidget],
parameter_name: str,
config: PyLiteralEditConfig,
):
super().__init__(parent, parameter_name, config)
def check_value_type(self, value: Any):
type_check(
value,
allowed_types=(bool, int, float, bytes, str, list, tuple, dict, set),
allow_none=True,
)
def _get_data(self, text: str) -> PyLiteralType:
text = text.strip()
try:
return ast.literal_eval(text)
except Exception as e:
raise ValueError(f"not a python literal: {e}") from e
def _set_data(self, data: PyLiteralType) -> str:
if not isinstance(data, str):
return str(data)
return repr(data)
| 2,191 | Python | .py | 57 | 30.22807 | 81 | 0.687718 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,473 | setedit.py | zimolab_PyGUIAdapter/pyguiadapter/widgets/basic/setedit.py | import dataclasses
from qtpy.QtWidgets import QWidget
from typing import Type, Optional, Any
from .base import StandaloneCodeEditorConfig
from .pyliteraledit import PyLiteralEdit, PyLiteralEditConfig, PyLiteralType
from ...utils import type_check
@dataclasses.dataclass(frozen=True)
class SetEditConfig(PyLiteralEditConfig):
"""SetEdit的配置类"""
default_value: Optional[set] = dataclasses.field(default_factory=set)
"""控件的默认值"""
height: Optional[int] = None
"""inplace编辑器的高度"""
width: Optional[int] = None
"""inplace编辑器的宽度"""
standalone_editor: bool = True
"""是否启用独立(standalone)代码编辑器"""
standalone_editor_button: bool = "Edit Set"
"""standalone编辑器启动按钮文本"""
standalone_editor_config: StandaloneCodeEditorConfig = dataclasses.field(
default_factory=StandaloneCodeEditorConfig
)
"""standalone编辑器配置"""
initial_text: str = "{}"
@classmethod
def target_widget_class(cls) -> Type["SetEdit"]:
return SetEdit
class SetEdit(PyLiteralEdit):
ConfigClass = SetEditConfig
def __init__(
self, parent: Optional[QWidget], parameter_name: str, config: SetEditConfig
):
super().__init__(parent, parameter_name, config)
def check_value_type(self, value: Any):
if value == "":
return
type_check(value, allowed_types=(set,), allow_none=True)
def _get_data(self, text: str) -> Optional[set]:
text = text.strip()
if text is None or text == "":
return None
if text == "{}":
return set()
data = super()._get_data(text)
if data is None:
return None
if not isinstance(data, set):
raise ValueError(f"not a set")
return data
def _set_data(self, data: PyLiteralType) -> str:
if data is None:
return "None"
if isinstance(data, str) and data.strip() == "":
return "None"
if not isinstance(data, set):
raise ValueError(f"not a set: {data}")
set_str = str(data)
if set_str.strip() == "set()":
return "{}"
return set_str
| 2,250 | Python | .py | 60 | 28.7 | 83 | 0.635005 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,474 | tupleedit.py | zimolab_PyGUIAdapter/pyguiadapter/widgets/basic/tupleedit.py | import dataclasses
from qtpy.QtWidgets import QWidget
from typing import Type, Optional, Any
from .base import StandaloneCodeEditorConfig
from .pyliteraledit import PyLiteralEdit, PyLiteralEditConfig, PyLiteralType
from ...utils import type_check
@dataclasses.dataclass(frozen=True)
class TupleEditConfig(PyLiteralEditConfig):
"""TupleEdit的配置类"""
default_value: Optional[tuple] = ()
"""控件的默认值"""
height: Optional[int] = None
"""inplace编辑器的高度"""
width: Optional[int] = None
"""inplace编辑器的宽度"""
standalone_editor: bool = True
"""是否启用独立(standalone)代码编辑器"""
standalone_editor_button: bool = "Edit Tuple"
"""standalone编辑器启动按钮文本"""
standalone_editor_config: StandaloneCodeEditorConfig = dataclasses.field(
default_factory=StandaloneCodeEditorConfig
)
"""standalone编辑器配置"""
initial_text: str = "()"
@classmethod
def target_widget_class(cls) -> Type["TupleEdit"]:
return TupleEdit
class TupleEdit(PyLiteralEdit):
ConfigClass = TupleEditConfig
def __init__(
self, parent: Optional[QWidget], parameter_name: str, config: TupleEditConfig
):
super().__init__(parent, parameter_name, config)
def check_value_type(self, value: Any):
type_check(value, (tuple,), allow_none=True)
def _get_data(self, text: str) -> Optional[tuple]:
text = text.strip()
if text is None or text == "":
return None
data = super()._get_data(text)
if data is None:
return None
if not isinstance(data, tuple):
raise ValueError(f"not a tuple")
return data
def _set_data(self, data: PyLiteralType) -> str:
if data is None:
return "None"
if isinstance(data, str) and data.strip() == "":
return "None"
if not isinstance(data, tuple):
raise ValueError(f"not a tuple: {data}")
return super()._set_data(data)
| 2,062 | Python | .py | 53 | 30.358491 | 85 | 0.659799 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,475 | dateedit.py | zimolab_PyGUIAdapter/pyguiadapter/widgets/basic/dateedit.py | import dataclasses
from datetime import date
from qtpy.QtCore import Qt, QDate
from qtpy.QtWidgets import QWidget, QDateEdit
from typing import Type, Union, Optional, Any
from ..common import (
CommonParameterWidgetConfig,
CommonParameterWidget,
)
from ...utils import type_check
Alignment = Qt.AlignmentFlag
TimeSpec = Qt.TimeSpec
@dataclasses.dataclass(frozen=True)
class DateEditConfig(CommonParameterWidgetConfig):
"""DateEdit的配置类。"""
default_value: Union[date, QDate, None] = date.today()
"""控件的默认值"""
min_date: Union[date, QDate, None] = None
"""控件的最小日期"""
max_date: Union[date, QDate, None] = None
"""控件的最大日期"""
display_format: Optional[str] = None
"""日期的显示格式,可以参考Qt官方文档:
[displayFormat](https://doc.qt.io/qtforpython-5/PySide2/QtWidgets/QDateTimeEdit.html#PySide2.QtWidgets.PySide2.QtWidgets.QDateTimeEdit.displayFormat)
"""
time_spec: Optional[TimeSpec] = None
"""时间日期标准,可以参考Qt官方文档:
[TimeSpec](https://doc.qt.io/qtforpython-5/PySide2/QtCore/Qt.html#PySide2.QtCore.PySide2.QtCore.Qt.TimeSpec)
"""
alignment: Alignment = Qt.AlignLeft | Qt.AlignVCenter
"""对齐方式,可选值有:AlignLeft、AlignRight、AlignCenter、AlignJustify等。"""
calendar_popup: bool = False
"""是否显示日历弹窗"""
@classmethod
def target_widget_class(cls) -> Type["DateEdit"]:
return DateEdit
class DateEdit(CommonParameterWidget):
ConfigClass = DateEditConfig
AlignLeft = Qt.AlignLeft
"""对齐方式:左对齐"""
AlignRight = Qt.AlignRight
"""对齐方式:右对齐"""
AlignCenter = Qt.AlignCenter
"""对齐方式:居中对齐"""
AlignJustify = Qt.AlignJustify
"""对齐方式:两端对齐"""
LocalTime = Qt.LocalTime
"""时间日期的标准:本地时间"""
UTC = Qt.UTC
"""时间日期的标准:UTC"""
OffsetFromUTC = Qt.OffsetFromUTC
"""时间日期的标准:OffsetFromUTC"""
TimeZone = Qt.TimeZone
"""时间日期的标准:TimeZone"""
def __init__(
self,
parent: Optional[QWidget],
parameter_name: str,
config: DateEditConfig,
):
self._value_widget: Optional[QDateEdit] = None
super().__init__(parent, parameter_name, config)
@property
def value_widget(self) -> QDateEdit:
self._config: DateEditConfig
if self._value_widget is None:
self._value_widget = QDateEdit(self)
if self._config.min_date is not None:
self._value_widget.setMinimumDate(QDate(self._config.min_date))
if self._config.max_date is not None:
self._value_widget.setMaximumDate(QDate(self._config.max_date))
if self._config.display_format is not None:
self._value_widget.setDisplayFormat(self._config.display_format)
if self._config.time_spec is not None:
self._value_widget.setTimeSpec(self._config.time_spec)
self._value_widget.setAlignment(self._config.alignment)
self._value_widget.setCalendarPopup(self._config.calendar_popup)
return self._value_widget
def check_value_type(self, value: Any):
type_check(value, (date, QDate), allow_none=True)
def set_value_to_widget(self, value: Union[date, QDate]):
if isinstance(value, QDate):
pass
elif isinstance(value, date):
value = QDate(value)
else:
raise TypeError(f"invalid type: {type(value)}")
self._value_widget.setDate(value)
def get_value_from_widget(self) -> date:
value = self._value_widget.date()
return value.toPython()
| 3,818 | Python | .py | 91 | 31.736264 | 153 | 0.669022 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,476 | datetimeedit.py | zimolab_PyGUIAdapter/pyguiadapter/widgets/basic/datetimeedit.py | import dataclasses
from datetime import datetime
from qtpy.QtCore import Qt, QDateTime
from qtpy.QtWidgets import QWidget, QDateTimeEdit
from typing import Type, Union, Optional, Any
from ..common import (
CommonParameterWidgetConfig,
CommonParameterWidget,
)
from ...utils import type_check
Alignment = Qt.AlignmentFlag
TimeSpec = Qt.TimeSpec
@dataclasses.dataclass(frozen=True)
class DateTimeEditConfig(CommonParameterWidgetConfig):
"""DateTimeEdit的配置类。"""
default_value: Union[datetime, QDateTime, None] = dataclasses.field(
default_factory=datetime.now
)
"""控件的默认值"""
min_datetime: Union[datetime, QDateTime, None] = None
"""时间日期的最小值"""
max_datetime: Union[datetime, QDateTime, None] = None
"""时间日期的最大值"""
display_format: Optional[str] = None
"""时间日期的显示格式。可参考Qt官方文档:
[displayFormat](https://doc.qt.io/qtforpython-5/PySide2/QtWidgets/QDateTimeEdit.html#PySide2.QtWidgets.PySide2.QtWidgets.QDateTimeEdit.displayFormat)
"""
time_spec: Optional[TimeSpec] = None
"""时间日期标准,可选值有:LocalTime、UTC、OffsetFromUTC、TimeZone。
可参考Qt官方文档:
[TimeSpec](https://doc.qt.io/qtforpython-5/PySide2/QtCore/Qt.html#PySide2.QtCore.PySide2.QtCore.Qt.TimeSpec)
"""
alignment: Alignment = Qt.AlignLeft | Qt.AlignVCenter
"""对齐方式,可选值有:AlignLeft、AlignRight、AlignCenter、AlignJustify等。"""
calendar_popup: bool = True
"""是否显示日历弹窗"""
@classmethod
def target_widget_class(cls) -> Type["DateTimeEdit"]:
return DateTimeEdit
class DateTimeEdit(CommonParameterWidget):
ConfigClass = DateTimeEditConfig
AlignLeft = Qt.AlignLeft
"""对齐方式:左对齐"""
AlignRight = Qt.AlignRight
"""对齐方式:右对齐"""
AlignCenter = Qt.AlignCenter
"""对齐方式:居中对齐"""
AlignJustify = Qt.AlignJustify
"""对齐方式:两端对齐"""
LocalTime = Qt.LocalTime
"""时间日期的标准:本地时间"""
UTC = Qt.UTC
"""时间日期的标准:UTC"""
OffsetFromUTC = Qt.OffsetFromUTC
"""时间日期的标准:OffsetFromUTC"""
TimeZone = Qt.TimeZone
"""时间日期的标准:TimeZone"""
def __init__(
self,
parent: Optional[QWidget],
parameter_name: str,
config: DateTimeEditConfig,
):
self._value_widget: Optional[QDateTimeEdit] = None
super().__init__(parent, parameter_name, config)
@property
def value_widget(self) -> QWidget:
self._config: DateTimeEditConfig
if self._value_widget is None:
self._value_widget = QDateTimeEdit(self)
if self._config.min_datetime is not None:
self._value_widget.setMinimumDateTime(
QDateTime(self._config.min_datetime)
)
if self._config.max_datetime is not None:
self._value_widget.setMaximumDateTime(
QDateTime(self._config.max_datetime)
)
if self._config.display_format is not None:
self._value_widget.setDisplayFormat(self._config.display_format)
if self._config.time_spec is not None:
self._value_widget.setTimeSpec(self._config.time_spec)
if self._config.alignment is not None:
self._value_widget.setAlignment(self._config.alignment)
self._value_widget.setCalendarPopup(self._config.calendar_popup)
return self._value_widget
def check_value_type(self, value: Any):
type_check(value, (datetime, QDateTime), allow_none=True)
def set_value_to_widget(self, value: Union[datetime, QDateTime]):
if isinstance(value, QDateTime):
pass
elif isinstance(value, datetime):
value = QDateTime(value)
else:
raise TypeError(f"invalid type: {type(value)}")
self._value_widget.setDateTime(value)
def get_value_from_widget(self) -> datetime:
value = self._value_widget.dateTime()
return value.toPython()
| 4,226 | Python | .py | 99 | 31.89899 | 153 | 0.670027 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,477 | floatspin.py | zimolab_PyGUIAdapter/pyguiadapter/widgets/basic/floatspin.py | import dataclasses
from typing import Type, Optional, Union, Any
from qtpy.QtWidgets import QWidget, QDoubleSpinBox
from ...exceptions import ParameterError
from ...utils import type_check
from ...widgets.common import (
CommonParameterWidgetConfig,
CommonParameterWidget,
)
@dataclasses.dataclass(frozen=True)
class FloatSpinBoxConfig(CommonParameterWidgetConfig):
default_value: Optional[float] = 0.0
"""控件的默认值"""
min_value: float = -2147483648.0
"""最小值"""
max_value: float = 2147483647.0
"""最大值"""
step: Optional[float] = 1.0
"""单次调整的步长"""
decimals: Optional[int] = 2
"""小数点后显示的位数"""
prefix: str = ""
"""前缀"""
suffix: str = ""
"""后缀"""
@classmethod
def target_widget_class(cls) -> Type["FloatSpinBox"]:
return FloatSpinBox
class FloatSpinBox(CommonParameterWidget):
ConfigClass: Type[FloatSpinBoxConfig] = FloatSpinBoxConfig
def __init__(
self, parent: Optional[QWidget], parameter_name: str, config: FloatSpinBoxConfig
):
self._value_widget: Optional[QDoubleSpinBox] = None
super().__init__(parent, parameter_name, config)
@property
def value_widget(self) -> QDoubleSpinBox:
if self._value_widget is None:
config: FloatSpinBoxConfig = self.config
self._value_widget = QDoubleSpinBox(self)
self._value_widget.setMinimum(config.min_value)
self._value_widget.setMaximum(config.max_value)
step = config.step
if step is not None and step > 0:
self._value_widget.setSingleStep(step)
decimals = config.decimals
if decimals is not None and decimals > 0:
self._value_widget.setDecimals(decimals)
self._value_widget.setPrefix(config.prefix or "")
self._value_widget.setSuffix(config.suffix or "")
return self._value_widget
def check_value_type(self, value: Any):
if value == "":
return
type_check(value, (float, int), allow_none=True)
def set_value_to_widget(self, value: Union[float, int, str]):
if value == "":
self._value_widget.setValue(0.0)
value = float(value)
self._value_widget.setValue(value)
def get_value_from_widget(self) -> float:
return self._value_widget.value()
| 2,432 | Python | .py | 62 | 30.806452 | 88 | 0.650481 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,478 | __init__.py | zimolab_PyGUIAdapter/pyguiadapter/widgets/basic/__init__.py | from .base import StandaloneCodeEditorConfig
from .intspin import IntSpinBoxConfig, IntSpinBox
from .boolbox import BoolBoxConfig, BoolBox
from .floatspin import FloatSpinBoxConfig, FloatSpinBox
from .pyliteraledit import (
PyLiteralEdit,
PyLiteralEditConfig,
PyLiteralType,
)
from .dictedit import DictEdit, DictEditConfig
from .listedit import ListEdit, ListEditConfig
from .tupleedit import TupleEdit, TupleEditConfig
from .setedit import SetEdit, SetEditConfig
from .enumselect import EnumSelect, EnumSelectConfig
from .base import BaseCodeEdit, BaseCodeEditConfig, BaseCodeFormatter
from .lineedit import LineEdit, LineEditConfig
from .exclusivechoice import ExclusiveChoiceBox, ExclusiveChoiceBoxConfig
from .datetimeedit import DateTimeEdit, DateTimeEditConfig
from .dateedit import DateEdit, DateEditConfig
from .timeedit import TimeEdit, TimeEditConfig
__all__ = [
"LineEdit",
"LineEditConfig",
"BoolBox",
"BoolBoxConfig",
"IntSpinBoxConfig",
"IntSpinBox",
"FloatSpinBoxConfig",
"FloatSpinBox",
"ExclusiveChoiceBox",
"ExclusiveChoiceBoxConfig",
"DateTimeEdit",
"DateTimeEditConfig",
"DateEdit",
"DateEditConfig",
"TimeEdit",
"TimeEditConfig",
"PyLiteralEdit",
"PyLiteralEditConfig",
"PyLiteralType",
"DictEdit",
"DictEditConfig",
"ListEdit",
"ListEditConfig",
"TupleEdit",
"TupleEditConfig",
"SetEdit",
"SetEditConfig",
"EnumSelect",
"EnumSelectConfig",
"BaseCodeEdit",
"BaseCodeEditConfig",
"BaseCodeFormatter",
"StandaloneCodeEditorConfig",
]
| 1,599 | Python | .py | 55 | 25.436364 | 73 | 0.772521 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,479 | timeedit.py | zimolab_PyGUIAdapter/pyguiadapter/widgets/basic/timeedit.py | import dataclasses
from datetime import time, datetime
from typing import Type, Union, Optional, Any
from qtpy.QtCore import Qt, QTime
from qtpy.QtWidgets import QWidget, QTimeEdit
from ..common import CommonParameterWidgetConfig, CommonParameterWidget
from ...utils import type_check
Alignment = Qt.AlignmentFlag
TimeSpec = Qt.TimeSpec
@dataclasses.dataclass(frozen=True)
class TimeEditConfig(CommonParameterWidgetConfig):
"""TimeEdit的配置类"""
default_value: Union[time, QTime, None] = datetime.now().time()
"""控件的默认值"""
min_time: Union[time, QTime, None] = None
"""控件的最小时间值"""
max_time: Union[time, QTime, None] = None
"""控件的最大时间值"""
display_format: Optional[str] = None
"""日期的显示格式,可以参考Qt官方文档:
[displayFormat](https://doc.qt.io/qtforpython-5/PySide2/QtWidgets/QDateTimeEdit.html#PySide2.QtWidgets.PySide2.QtWidgets.QDateTimeEdit.displayFormat)
"""
time_spec: Optional[TimeSpec] = None
"""时间日期标准,可以参考Qt官方文档:
[TimeSpec](https://doc.qt.io/qtforpython-5/PySide2/QtCore/Qt.html#PySide2.QtCore.PySide2.QtCore.Qt.TimeSpec)
"""
alignment: Alignment = Qt.AlignLeft | Qt.AlignVCenter
"""对齐方式,可选值有:AlignLeft、AlignRight、AlignCenter、AlignJustify等。"""
@classmethod
def target_widget_class(cls) -> Type["TimeEdit"]:
return TimeEdit
class TimeEdit(CommonParameterWidget):
ConfigClass = TimeEditConfig
AlignLeft = Qt.AlignLeft
"""对齐方式:左对齐"""
AlignRight = Qt.AlignRight
"""对齐方式:右对齐"""
AlignCenter = Qt.AlignCenter
"""对齐方式:居中对齐"""
AlignJustify = Qt.AlignJustify
"""对齐方式:两端对齐"""
LocalTime = Qt.LocalTime
"""时间日期的标准:本地时间"""
UTC = Qt.UTC
"""时间日期的标准:UTC"""
OffsetFromUTC = Qt.OffsetFromUTC
"""时间日期的标准:OffsetFromUTC"""
TimeZone = Qt.TimeZone
"""时间日期的标准:TimeZone"""
def __init__(
self,
parent: Optional[QWidget],
parameter_name: str,
config: TimeEditConfig,
):
self._value_widget: Optional[QTimeEdit] = None
super().__init__(parent, parameter_name, config)
@property
def value_widget(self) -> QWidget:
self._config: TimeEditConfig
if self._value_widget is None:
self._value_widget = QTimeEdit(self)
if self._config.min_time is not None:
self._value_widget.setMinimumTime(QTime(self._config.min_time))
if self._config.max_time is not None:
self._value_widget.setMaximumTime(QTime(self._config.max_time))
if self._config.display_format is not None:
self._value_widget.setDisplayFormat(self._config.display_format)
if self._config.time_spec is not None:
self._value_widget.setTimeSpec(self._config.time_spec)
self._value_widget.setAlignment(self._config.alignment)
return self._value_widget
def check_value_type(self, value: Any):
type_check(value, allowed_types=(time, QTime), allow_none=True)
def set_value_to_widget(self, value: Union[time, QTime]):
if isinstance(value, QTime):
pass
elif isinstance(value, time):
value = QTime(value)
else:
raise TypeError(f"invalid type: {type(value)}")
self._value_widget.setTime(value)
def get_value_from_widget(self) -> time:
value = self._value_widget.time()
return value.toPython()
| 3,695 | Python | .py | 85 | 33.082353 | 153 | 0.672539 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,480 | base.py | zimolab_PyGUIAdapter/pyguiadapter/widgets/basic/base.py | import dataclasses
import warnings
from abc import abstractmethod
from typing import Type, TypeVar, Callable, Tuple, Optional, Union
from pyqcodeeditor.QCodeEditor import QCodeEditor
from pyqcodeeditor.QStyleSyntaxHighlighter import QStyleSyntaxHighlighter
from qtpy.QtCore import Qt
from qtpy.QtWidgets import QWidget, QVBoxLayout, QPushButton
from ..common import (
CommonParameterWidget,
CommonParameterWidgetConfig,
)
from ...codeeditor import (
BaseCodeFormatter,
CodeEditorWindow,
CodeEditorConfig,
LineWrapMode,
WordWrapMode,
create_highlighter,
)
from ...codeeditor.constants import (
MENU_FILE,
ACTION_SAVE,
ACTION_SAVE_AS,
CONFIRM_DIALOG_TITLE,
)
from ...exceptions import ParameterError
from ...utils import messagebox
from ...window import SimpleWindowEventListener
T = TypeVar("T")
CONFIRM_MSG = "Do you want to keep the changes?"
STANDALONE_EDITOR_BUTTON = "Edit"
STANDALONE_EDITOR_TITLE = "Parameter - {}"
LINE_WRAP_WIDTH = 88
INDENT_SIZE = 4
EDITOR_HEIGHT = 110
EDITOR_WIDTH = 230
@dataclasses.dataclass
class StandaloneCodeEditorConfig(object):
"""standalone编辑器配置类"""
title: str = STANDALONE_EDITOR_TITLE
"""standalone编辑器窗口标题"""
text_font_family: Optional[str] = None
"""standalone编辑器字体"""
text_font_size: Optional[int] = None
"""standalone编辑器字体大小"""
line_wrap_mode: LineWrapMode = LineWrapMode.NoWrap
"""standalone编辑器行折叠模式"""
line_wrap_width: int = LINE_WRAP_WIDTH
"""standalone编辑器行折叠宽度"""
word_wrap_mode: WordWrapMode = WordWrapMode.NoWrap
"""standalone编辑器字词折叠模式"""
file_filters: Optional[str] = None
"""standalone编辑器文件对话框的文件过滤器"""
start_dir: Optional[str] = None
"""standalone编辑器文件对话框的起始目录"""
use_default_menus: bool = True
"""是否使用默认菜单栏"""
excluded_menus: Tuple[str] = ()
"""禁用的默认菜单"""
excluded_menu_actions: Tuple[Tuple[str, str]] = (
(MENU_FILE, ACTION_SAVE),
(MENU_FILE, ACTION_SAVE_AS),
)
"""禁用的默认菜单项"""
use_default_toolbar: bool = True
"""是否启用默认工具栏"""
excluded_toolbar_actions: Tuple[str] = (
ACTION_SAVE,
ACTION_SAVE_AS,
)
"""禁用的默认工具栏项"""
confirm_dialog: bool = True
"""standalone编辑器退出时是否显示确认对话框"""
confirm_dialog_title: str = CONFIRM_DIALOG_TITLE
"""确认对话框标题"""
confirm_dialog_message: str = CONFIRM_MSG
"""确认对话框显示的内容"""
@dataclasses.dataclass(frozen=True)
class BaseCodeEditConfig(CommonParameterWidgetConfig):
"""BaseCodeEdit的配置类"""
# 以下属性适用于inplace编辑器
text_font_size: Optional[int] = None
"""inplace编辑器字体大小"""
text_font_family: Optional[str] = None
"""inplace编辑器字体"""
width: Optional[int] = EDITOR_WIDTH
"""inplace编辑器宽度"""
height: Optional[int] = EDITOR_HEIGHT
"""inplace编辑器高度"""
line_wrap_mode: LineWrapMode = LineWrapMode.WidgetWidth
"""inplace编辑器行折叠模式"""
line_wrap_width: int = LINE_WRAP_WIDTH
"""inplace编辑器行折叠宽度"""
word_wrap_mode: WordWrapMode = WordWrapMode.WordWrap
"""inplace编辑器字词折叠模式"""
initial_text: Optional[str] = None
"""inplace编辑器的初始文本"""
standalone_editor: bool = True
"""是否启用standalone编辑器"""
standalone_editor_button: str = STANDALONE_EDITOR_BUTTON
"""standalone编辑器窗口打开按钮的文本"""
standalone_editor_config: StandaloneCodeEditorConfig = dataclasses.field(
default_factory=StandaloneCodeEditorConfig
)
"""standalone编辑器配置"""
# 以下属性同时适用于inplace和standalone编辑器
indent_size: int = INDENT_SIZE
"""缩进大小,该属性适用于inplace编辑器和standalone编辑器"""
auto_indent: bool = True
"""是否自动缩进,该属性适用于inplace编辑器和standalone编辑器"""
auto_parentheses: bool = True
"""是否自动匹配括号, 该属性适用于inplace编辑器和standalone编辑器"""
formatter: Union[BaseCodeFormatter, Callable[[str], str], None] = None
"""代码格式化器,该属性适用于inplace编辑器和standalone编辑器"""
highlighter: Optional[Type[QStyleSyntaxHighlighter]] = None
"""语法高亮器类,该属性适用于inplace编辑器和standalone编辑器"""
highlighter_args: Union[dict, list, tuple, None] = None
"""语法高亮器参数,该属性适用于inplace编辑器和standalone编辑器"""
@classmethod
@abstractmethod
def target_widget_class(cls) -> Type["BaseCodeEdit"]:
pass
class BaseCodeEdit(CommonParameterWidget):
ConfigClass = BaseCodeEditConfig
def __init__(
self,
parent: Optional[QWidget],
parameter_name: str,
config: BaseCodeEditConfig,
):
self._value_widget: Optional[QWidget] = None
self._editor_button: Optional[QPushButton] = None
super().__init__(parent, parameter_name, config)
self._inplace_editor: Optional[QCodeEditor] = None
self._standalone_editor: Optional[CodeEditorWindow] = None
@property
def value_widget(self) -> QWidget:
if self._value_widget is None:
config: BaseCodeEditConfig = self.config
self._value_widget = QWidget(self)
layout = QVBoxLayout()
layout.setContentsMargins(0, 0, 0, 0)
self._value_widget.setLayout(layout)
self._inplace_editor = QCodeEditor(self._value_widget)
layout.addWidget(self._inplace_editor)
if config.standalone_editor:
self._editor_button = QPushButton(self._value_widget)
self._editor_button.setText(
config.standalone_editor_button or STANDALONE_EDITOR_BUTTON
)
# noinspection PyUnresolvedReferences
self._editor_button.clicked.connect(self._on_open_standalone_editor)
layout.addWidget(self._editor_button)
# if config.min_height and config.min_height > 0:
# self._inplace_editor.setMinimumHeight(config.min_height)
#
# if config.min_width and config.min_width > 0:
# self._inplace_editor.setMinimumWidth(config.min_width)
if config.height is not None and config.height >= 0:
if config.height == 0:
self._inplace_editor.setVisible(False)
self._inplace_editor.setFixedHeight(config.height)
if config.width is not None and config.width >= 0:
if config.width == 0:
self._inplace_editor.setVisible(False)
self._inplace_editor.setFixedWidth(config.width)
self._inplace_editor.setPlainText(config.initial_text or "")
highlighter = create_highlighter(
config.highlighter, config.highlighter_args
)
highlighter.setParent(self)
self._inplace_editor.setHighlighter(highlighter)
self._inplace_editor.setTabReplace(True)
self._inplace_editor.setTabReplaceSize(config.indent_size)
self._inplace_editor.setLineWrapMode(config.line_wrap_mode)
if (
config.line_wrap_width
in (
LineWrapMode.FixedPixelWidth,
LineWrapMode.FixedColumnWidth,
)
and config.line_wrap_width > 0
):
self._inplace_editor.setLineWrapWidth(config.line_wrap_width)
self._inplace_editor.setWordWrapMode(config.word_wrap_mode)
if config.text_font_size and config.text_font_size > 0:
self._inplace_editor.setFontSize(config.text_font_size)
if config.text_font_family and config.text_font_family.strip() != "":
self._inplace_editor.setFontFamily(config.text_font_family)
return self._value_widget
def _on_open_standalone_editor(self):
if self._standalone_editor is not None:
self._standalone_editor.close()
self._standalone_editor.deleteLater()
self._standalone_editor = None
config: BaseCodeEditConfig = self.config
standalone_config = config.standalone_editor_config
event_listener = SimpleWindowEventListener(
on_close=self._on_standalone_editor_close
)
editor_config = CodeEditorConfig(
initial_text=self._inplace_editor.toPlainText(),
formatter=config.formatter,
highlighter=config.highlighter,
highlighter_args=config.highlighter_args,
check_unsaved_changes=False,
show_filename_in_title=False,
title=standalone_config.title.format(self.parameter_name),
auto_indent=config.auto_indent,
auto_parentheses=config.auto_parentheses,
file_filters=standalone_config.file_filters,
start_dir=standalone_config.start_dir,
line_wrap_mode=standalone_config.line_wrap_mode,
line_wrap_width=standalone_config.line_wrap_width,
word_wrap_mode=standalone_config.word_wrap_mode,
text_font_size=standalone_config.text_font_size,
text_font_family=standalone_config.text_font_family,
tab_replace=True,
tab_size=config.indent_size,
no_file_mode=True,
use_default_menus=standalone_config.use_default_menus,
use_default_toolbar=standalone_config.use_default_toolbar,
excluded_menus=standalone_config.excluded_menus,
excluded_menu_actions=standalone_config.excluded_menu_actions,
excluded_toolbar_actions=standalone_config.excluded_toolbar_actions,
)
self._standalone_editor = CodeEditorWindow(
self, editor_config, listener=event_listener
)
self._standalone_editor.setWindowModality(Qt.WindowModal)
self._standalone_editor.setAttribute(Qt.WA_DeleteOnClose, True)
self._standalone_editor.destroyed.connect(self._on_standalone_editor_destroyed)
self._standalone_editor.show()
def _on_standalone_editor_close(self, editor: CodeEditorWindow) -> bool:
standalone_config = self.config.standalone_editor_config
if editor.is_modified():
if not standalone_config.confirm_dialog:
new_code_text = editor.get_text()
self._inplace_editor.setPlainText(new_code_text)
return True
# noinspection PyUnresolvedReferences
ret = messagebox.show_question_message(
self,
title=standalone_config.confirm_dialog_title,
message=standalone_config.confirm_dialog_message,
buttons=messagebox.Yes | messagebox.No,
)
if ret == messagebox.Yes:
new_code_text = editor.get_text().rstrip()
self._inplace_editor.setPlainText(new_code_text)
return True
def _on_standalone_editor_destroyed(self):
self._standalone_editor = None
def _do_format(self, code: str) -> Optional[str]:
config: BaseCodeEditConfig = self.config
if config.formatter:
try:
formatted = config.formatter.format_code(code)
return formatted.rstrip()
except Exception as e:
warnings.warn(f"Failed to format code: {e}")
return None
return None
@abstractmethod
def _get_data(self, text: str) -> T:
pass
@abstractmethod
def _set_data(self, data: T) -> str:
pass
def set_value_to_widget(self, value: T):
try:
code_text = self._set_data(value)
except Exception as e:
raise ParameterError(
parameter_name=self.parameter_name, message=str(e)
) from e
else:
formatted = self._do_format(code_text)
if formatted is not None:
self._inplace_editor.setPlainText(formatted)
else:
self._inplace_editor.setPlainText(code_text)
def get_value_from_widget(self) -> T:
try:
obj = self._get_data(self._inplace_editor.toPlainText())
except Exception as e:
raise ParameterError(
parameter_name=self.parameter_name, message=str(e)
) from e
return obj
| 12,834 | Python | .py | 291 | 32.353952 | 87 | 0.651591 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,481 | intspin.py | zimolab_PyGUIAdapter/pyguiadapter/widgets/basic/intspin.py | import dataclasses
import warnings
from typing import Type, Optional, Union, Any
from qtpy.QtWidgets import QWidget, QSpinBox
from ...utils import type_check
from ...widgets.common import (
CommonParameterWidgetConfig,
CommonParameterWidget,
)
@dataclasses.dataclass(frozen=True)
class IntSpinBoxConfig(CommonParameterWidgetConfig):
"""IntSpinBox配置类"""
default_value: Optional[int] = 0
"""控件的默认值"""
min_value: int = -2147483648
"""最小值"""
max_value: int = 2147483647
"""最大值"""
step: int = 1
"""单次调整的步长"""
prefix: str = ""
"""前缀"""
suffix: str = ""
"""后缀"""
display_integer_base: int = 10
"""整数显示进制"""
@classmethod
def target_widget_class(cls) -> Type["IntSpinBox"]:
return IntSpinBox
class IntSpinBox(CommonParameterWidget):
"""
整数输入框控件,SpinBox形式。是`int`类型参数的默认控件。
"""
ConfigClass: Type[IntSpinBoxConfig] = IntSpinBoxConfig
def __init__(
self, parent: Optional[QWidget], parameter_name: str, config: IntSpinBoxConfig
):
self._value_widget: Optional[QSpinBox] = None
super().__init__(parent, parameter_name, config)
assert config.max_value >= config.min_value
@property
def value_widget(self) -> QSpinBox:
if self._value_widget is None:
config: IntSpinBoxConfig = self.config
self._value_widget = QSpinBox(self)
self._value_widget.setMaximum(config.max_value)
self._value_widget.setMinimum(config.min_value)
self._value_widget.setSingleStep(config.step)
self._value_widget.setPrefix(config.prefix or "")
self._value_widget.setSuffix(config.suffix or "")
if config.display_integer_base > 1:
self._value_widget.setDisplayIntegerBase(config.display_integer_base)
else:
warnings.warn(
f"invalid display_integer_base value, this will be ignored: {config.display_integer_base}"
)
return self._value_widget
def check_value_type(self, value: Any):
if value == "":
return
type_check(value, (int, bool), allow_none=True)
def set_value_to_widget(self, value: Union[int, bool]):
if value == "":
self._value_widget.setValue(0)
return
value = int(value)
self._value_widget.setValue(value)
def get_value_from_widget(self) -> int:
return self._value_widget.value()
| 2,611 | Python | .py | 69 | 28.652174 | 110 | 0.636552 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,482 | lineedit.py | zimolab_PyGUIAdapter/pyguiadapter/widgets/basic/lineedit.py | import dataclasses
from qtpy.QtCore import QRegularExpression, Qt
from qtpy.QtGui import QValidator, QRegularExpressionValidator
from qtpy.QtWidgets import QWidget, QLineEdit
from typing import Type, Optional, Union
from ..common import CommonParameterWidget, CommonParameterWidgetConfig
EchoMode = QLineEdit.EchoMode
"""LineEdit的回显模式"""
Alignment = Qt.AlignmentFlag
"""LineEdit中的对齐方式"""
@dataclasses.dataclass(frozen=True)
class LineEditConfig(CommonParameterWidgetConfig):
"""LineEdit配置类"""
default_value: Optional[str] = ""
"""默认值"""
placeholder: str = ""
"""占位文本,输入框为空时将显示该文本"""
clear_button: bool = False
"""是否显示清除按钮"""
echo_mode: Optional[EchoMode] = None
"""回显模式,默认为Normal"""
alignment: Optional[Alignment] = None
"""输入文本的对齐方式,默认为AlignLeft"""
input_mask: Optional[str] = None
"""输入掩码,用于限制用户输入,可以参考:https://doc.qt.io/qt-5/qlineedit.html#inputMask-prop"""
max_length: Optional[int] = None
"""最大长度"""
validator: Union[QValidator, str, None] = None
"""输入验证器,可以是QValidator对象,也可以是正则表达式字符串,默认无验证器"""
drag_enabled: bool = True
"""是否允许拖拽"""
frame: bool = True
"""是否显示边框"""
readonly: bool = False
"""是否只读"""
@classmethod
def target_widget_class(cls) -> Type["LineEdit"]:
return LineEdit
class LineEdit(CommonParameterWidget):
ConfigClass = LineEditConfig
PasswordEchoMode = EchoMode.Password
"""回显模式:显示为密码"""
PasswordEchoOnEditMode = EchoMode.PasswordEchoOnEdit
"""回显模式:输入时正常显示,输入结束后显示为密码"""
NormalEchoMode = EchoMode.Normal
"""回显模式:正常显示"""
NoEchoMode = EchoMode.NoEcho
"""回显模式:隐藏输入内容"""
AlignLeft = Alignment.AlignRight
"""文本对齐方式:左对齐"""
AlignRight = Alignment.AlignRight
"""文本对齐方式:右对齐"""
AlignCenter = Alignment.AlignCenter
"""文本对齐方式:居中对齐"""
def __init__(
self, parent: Optional[QWidget], parameter_name: str, config: LineEditConfig
):
self._value_widget: Optional[QLineEdit] = None
super().__init__(parent, parameter_name, config)
@property
def value_widget(self) -> QLineEdit:
if self._value_widget is None:
config: LineEditConfig = self.config
self._value_widget = QLineEdit("", self)
self._value_widget.setPlaceholderText(config.placeholder or "")
self._value_widget.setClearButtonEnabled(config.clear_button)
if config.echo_mode is not None:
self._value_widget.setEchoMode(config.echo_mode)
if config.input_mask:
self._value_widget.setInputMask(config.input_mask)
max_length = config.max_length
if isinstance(max_length, int):
max_length = max(max_length, 1)
self._value_widget.setMaxLength(max_length)
validator = config.validator
if isinstance(validator, str):
regex = QRegularExpression(validator)
validator = QRegularExpressionValidator(self._value_widget)
validator.setRegularExpression(regex)
assert isinstance(validator, (QValidator, type(None)))
if validator:
self._value_widget.setValidator(validator)
if config.alignment is not None:
self._value_widget.setAlignment(config.alignment)
self._value_widget.setFrame(config.frame is True)
self._value_widget.setDragEnabled(config.drag_enabled is True)
self._value_widget.setReadOnly(config.readonly is True)
return self._value_widget
def set_value_to_widget(self, value: str):
self.value_widget.setText(str(value))
def get_value_from_widget(self) -> str:
if not self._value_widget.hasAcceptableInput():
raise ValueError("unacceptable input: validation failed")
return self.value_widget.text()
| 4,328 | Python | .py | 94 | 33.585106 | 84 | 0.6703 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,483 | stringlist.py | zimolab_PyGUIAdapter/pyguiadapter/widgets/extend/stringlist.py | import dataclasses
import os.path
from typing import Type, List, Literal, Optional, Any
from qtpy.QtCore import QStringListModel, Qt
from qtpy.QtWidgets import QWidget, QListView, QVBoxLayout, QPushButton, QMenu, QAction
from ..common import CommonParameterWidgetConfig, CommonParameterWidget
from ... import utils
from ...utils import type_check
TextElideMode = Qt.TextElideMode
ElideLeft = TextElideMode.ElideLeft
ElideMiddle = TextElideMode.ElideMiddle
ElideRight = TextElideMode.ElideRight
ElideNone = TextElideMode.ElideNone
@dataclasses.dataclass(frozen=True)
class StringListEditConfig(CommonParameterWidgetConfig):
"""StringListEdit的配置类。"""
default_value: Optional[List[str]] = dataclasses.field(default_factory=list)
"""默认值"""
empty_string_strategy: Literal["keep_all", "keep_one", "remove_all"] = "remove_all"
"""对待列表中空字符串的策略,keep_all表示保留所有空字符串,keep_one表示只保留第一个空字符串,remove_all表示删除所有空字符串"""
add_file: bool = True
"""是否开启添加文件路径功能"""
add_dir: bool = True
"""是否开启添加文件夹路径功能"""
file_filters: str = ""
"""文件过滤器,用于文件对话框"""
start_dir: str = ""
"""起始路径,用于文件对话框"""
normalize_path: bool = True
"""是否将路径规范化"""
add_button_text: str = "Add"
"""添加按钮文本"""
remove_button_text: str = "Remove"
"""移除按钮文本"""
clear_button_text: str = "Clear"
"""清空按钮文本"""
add_string_hint: str = "Add Text"
"""添加字符串的提示"""
add_file_hint: str = "Add File"
"""添加文件路径的提示"""
add_dir_hint: str = "Add Directory"
"""添加文件夹路径的提示"""
file_dialog_title: str = "Select File"
"""添加文件对话框标题"""
dir_dialog_title: str = "Select Directory"
"""添加文件夹对话框标题"""
confirm_dialog_title: str = "Confirm"
"""确认对话框标题"""
warning_dialog_title: str = "Warning"
"""警告对话框标题"""
confirm_remove: bool = True
"""是否显示移除确认对话框"""
confirm_clear: bool = True
"""是否显示清空确认对话框"""
remove_confirm_message: str = "Are you sure to remove the selected item(s)?"
"""移除确认对话框消息"""
clear_confirm_message: str = "Are you sure to clear all of the items?"
"""清空确认对话框消息"""
no_selection_message: str = "No items are selected!"
"""未选择任何项的提示"""
drag_enabled: bool = True
"""是否允许拖拽"""
wrapping: bool = False
"""是否允许换行"""
text_elide_mode: TextElideMode = TextElideMode.ElideLeft
"""文本省略模式"""
alternating_row_colors: bool = True
"""是否使用交替行颜色"""
width: Optional[int] = None
"""表格的最小宽度"""
height: Optional[int] = 230
"""表格的最小高度"""
@classmethod
def target_widget_class(cls) -> Type["StringListEdit"]:
return StringListEdit
class StringListEdit(CommonParameterWidget):
ConfigClass = StringListEditConfig
def __init__(
self,
parent: Optional[QWidget],
parameter_name: str,
config: StringListEditConfig,
):
self._value_widget: Optional[QWidget] = None
self._list_view: Optional[QListView] = None
self._add_button: Optional[QPushButton] = None
self._remove_button: Optional[QPushButton] = None
self._clear_button: Optional[QPushButton] = None
self._model: Optional[QStringListModel] = None
super().__init__(parent, parameter_name, config)
@property
def value_widget(self) -> QWidget:
self._config: StringListEditConfig
if self._value_widget is None:
self._value_widget = QWidget(self)
layout_main = QVBoxLayout()
layout_main.setContentsMargins(0, 0, 0, 0)
layout_main.setSpacing(0)
self._value_widget.setLayout(layout_main)
self._list_view = QListView(self._value_widget)
if self._config.height is not None and self._config.height > 0:
self._list_view.setMinimumHeight(self._config.height)
if self._config.width is not None and self._config.width > 0:
self._list_view.setMinimumWidth(self._config.width)
if self._config.drag_enabled:
self._list_view.setDragDropMode(QListView.InternalMove)
self._list_view.setDefaultDropAction(Qt.DropAction.TargetMoveAction)
self._list_view.setMovement(QListView.Snap)
self._list_view.setDragDropOverwriteMode(False)
self._list_view.setWrapping(self._config.wrapping)
self._list_view.setTextElideMode(self._config.text_elide_mode)
self._list_view.setAlternatingRowColors(self._config.alternating_row_colors)
self._model = QStringListModel(self._value_widget)
self._list_view.setModel(self._model)
layout_main.addWidget(self._list_view)
layout_buttons = QVBoxLayout()
self._add_button = self._create_add_button(self._value_widget)
layout_buttons.addWidget(self._add_button)
self._remove_button = QPushButton(self._value_widget)
self._remove_button.setText(self._config.remove_button_text)
# noinspection PyUnresolvedReferences
self._remove_button.clicked.connect(self._on_remove_item)
layout_buttons.addWidget(self._remove_button)
self._clear_button = QPushButton(self._value_widget)
# noinspection PyUnresolvedReferences
self._clear_button.clicked.connect(self._on_clear_items)
self._clear_button.setText(self._config.clear_button_text)
layout_buttons.addWidget(self._clear_button)
layout_main.addLayout(layout_buttons)
return self._value_widget
def _create_add_button(self, parent: QWidget) -> QPushButton:
self._config: StringListEditConfig
add_button = QPushButton(parent)
add_button.setText(self._config.add_button_text)
if self._config.add_file or self._config.add_dir:
menu = QMenu(add_button)
action_add_string = QAction(menu)
action_add_string.setText(self._config.add_string_hint)
# noinspection PyUnresolvedReferences
action_add_string.triggered.connect(self._on_add_item)
menu.addAction(action_add_string)
if self._config.add_file:
action_add_file = QAction(menu)
action_add_file.setText(self._config.add_file_hint)
# noinspection PyUnresolvedReferences
action_add_file.triggered.connect(self._on_add_file)
menu.addAction(action_add_file)
if self._config.add_dir:
action_add_dir = QAction(menu)
action_add_dir.setText(self._config.add_dir_hint)
# noinspection PyUnresolvedReferences
action_add_dir.triggered.connect(self._on_add_dir)
menu.addAction(action_add_dir)
add_button.setMenu(menu)
else:
# noinspection PyUnresolvedReferences
add_button.clicked.connect(self._on_add_item)
return add_button
def check_value_type(self, value: Any):
type_check(value, (list,), allow_none=True)
def set_value_to_widget(self, value: List[str]):
self._clear_items()
self._append_items(value)
def get_value_from_widget(self) -> List[str]:
self._config: StringListEditConfig
string_list = self._model.stringList()
if self._config.empty_string_strategy == "keep_all":
return [str(item) for item in string_list]
elif self._config.empty_string_strategy == "keep_one":
return self._keep_one_empty_item(string_list)
else:
return [str(item) for item in string_list if item != "" or item is not None]
def _on_add_item(self):
self._append_item("", edit=True, set_current=True)
def _on_remove_item(self):
self._config: StringListEditConfig
selected = self._list_view.selectedIndexes()
if not selected:
utils.show_warning_message(
self,
self._config.no_selection_message,
title=self._config.warning_dialog_title,
)
return
if self._config.confirm_remove:
ret = utils.show_question_message(
self,
message=self._config.remove_confirm_message,
title=self._config.warning_dialog_title,
buttons=utils.Yes | utils.No,
)
if ret == utils.No:
return
for index in selected:
self._model.removeRow(index.row())
def _on_clear_items(self):
self._config: StringListEditConfig
count = self._model.rowCount()
if count <= 0:
return
if self._config.confirm_remove:
ret = utils.show_question_message(
self,
message=self._config.clear_confirm_message,
title=self._config.warning_dialog_title,
buttons=utils.Yes | utils.No,
)
if ret == utils.No:
return
self._clear_items()
def _on_add_file(self):
self._config: StringListEditConfig
path = utils.get_open_file(
self,
title=self._config.file_dialog_title,
start_dir=self._config.start_dir,
filters=self._config.file_filters,
)
if not path:
return
if self._config.normalize_path:
path = os.path.normpath(path)
current_idx = self._list_view.currentIndex()
if not current_idx or (not current_idx.isValid()):
self._append_item(path, set_current=False)
else:
self._model.setData(current_idx, path)
def _on_add_dir(self):
self._config: StringListEditConfig
path = utils.get_existing_directory(
self,
title=self._config.file_dialog_title,
start_dir=self._config.start_dir,
)
if not path:
return
if self._config.normalize_path:
path = os.path.normpath(path)
current_idx = self._list_view.currentIndex()
if not current_idx or (not current_idx.isValid()):
self._append_item(path, set_current=True)
else:
self._model.setData(current_idx, path)
def _clear_items(self):
self._model.removeRows(0, self._model.rowCount())
self._model.setStringList([])
def _append_item(self, item: str, edit: bool = False, set_current: bool = False):
if item is None:
item = ""
row = self._model.rowCount()
self._model.insertRow(row)
self._model.setData(self._model.index(row), str(item))
if edit:
self._list_view.edit(self._model.index(row))
if set_current:
self._list_view.setCurrentIndex(self._model.index(row))
def _append_items(self, items: List[str]):
for item in items:
self._append_item(item)
@staticmethod
def _keep_one_empty_item(items: List[str]) -> List[str]:
should_add = True
ret = []
for item in items:
if item is None:
item = ""
item = str(item)
if item != "":
ret.append(item)
continue
# if item == "" and
if should_add:
ret.append(item)
should_add = False
return ret
| 11,961 | Python | .py | 275 | 31.701818 | 88 | 0.615892 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,484 | choicebox.py | zimolab_PyGUIAdapter/pyguiadapter/widgets/extend/choicebox.py | import dataclasses
from typing import Type, Any, Dict, Optional, Union, Sequence
from qtpy.QtCore import Qt
from qtpy.QtGui import QKeyEvent
from qtpy.QtWidgets import QWidget, QComboBox
from ..common import CommonParameterWidgetConfig, CommonParameterWidget
# noinspection PyPep8Naming
class _FIRST_ITEM(object):
__slots__ = ()
@dataclasses.dataclass
class _DataWrap(object):
value: Any
@classmethod
def unwrap(cls, data: Any) -> Any:
if isinstance(data, cls):
return data.value
return data
class _ChoiceComboBox(QComboBox):
def __init__(self, parent: Optional[QWidget] = None, add_user_input: bool = True):
super().__init__(parent)
self._add_user_input = add_user_input
@property
def add_user_input(self) -> bool:
return self._add_user_input
@add_user_input.setter
def add_user_input(self, value: bool):
self._add_user_input = value
def keyPressEvent(self, e: QKeyEvent):
if self._add_user_input:
super().keyPressEvent(e)
return
if e.key() == Qt.Key_Enter or e.key() == Qt.Key_Return:
e.ignore()
return
super().keyPressEvent(e)
@dataclasses.dataclass(frozen=True)
class ChoiceBoxConfig(CommonParameterWidgetConfig):
"""ChoiceBox的配置类"""
default_value: Optional[Any] = _FIRST_ITEM
"""默认选项,`_FIRST_ITEM`是一个特殊值,表示选择选项列表中的第一个"""
choices: Union[Dict[str, Any], Sequence[Any]] = dataclasses.field(
default_factory=list
)
"""选项列表,可以是字典或列表、元组等序列对象。为字典时,键值对的键为显示文本,值为实际值;为序列对象时,对序列中的每个元素调用`str()`,
以其返回值作为显示文本,元素本身作为实际值。"""
editable: bool = False
"""是否允许编辑"""
add_user_input: bool = True
"""在`editable`为`True`时,用户输入的内容是否作为新的选项添加到选项列表中"""
@classmethod
def target_widget_class(cls) -> Type["ChoiceBox"]:
return ChoiceBox
class ChoiceBox(CommonParameterWidget):
ConfigClass = ChoiceBoxConfig
def __init__(
self,
parent: Optional[QWidget],
parameter_name: str,
config: ChoiceBoxConfig,
):
self._value_widget: Optional[_ChoiceComboBox] = None
super().__init__(parent, parameter_name, config)
@property
def value_widget(self) -> QWidget:
self._config: ChoiceBoxConfig
if self._value_widget is None:
self._value_widget = _ChoiceComboBox(self, self._config.add_user_input)
self._value_widget.setEditable(self._config.editable is True)
self._add_choices()
return self._value_widget
def set_value_to_widget(self, value: Any):
if value is _FIRST_ITEM:
self._value_widget.setCurrentIndex(0)
return
for index in range(self._value_widget.count()):
data = self._value_widget.itemData(index, Qt.UserRole)
if isinstance(data, _DataWrap):
data = data.value
if data == value:
self._value_widget.setCurrentIndex(index)
break
def get_value_from_widget(self) -> Any:
if self._value_widget.isEditable():
# For an editable ChoiceBox, if the currentText() is not consistent with itemText(currentIndex()), it means
# the user has input a new text, in this case, we should return the new input text, otherwise we should
# return the currentData().
current_text = self._value_widget.currentText()
item_text = self._value_widget.itemText(self._value_widget.currentIndex())
if current_text != item_text:
return current_text
data = _DataWrap.unwrap(self._value_widget.currentData(Qt.UserRole))
if data is not None:
return data
else:
return current_text
data = _DataWrap.unwrap(self._value_widget.currentData(Qt.UserRole))
if data is not None:
return data
else:
return self._value_widget.currentText()
def _add_choices(self):
self._config: ChoiceBoxConfig
choices = self._config.choices
if isinstance(choices, dict):
for key, value in choices.items():
self._value_widget.addItem(key, _DataWrap(value))
return
if isinstance(choices, (list, tuple, set)):
for choice in choices:
self._value_widget.addItem(str(choice), _DataWrap(choice))
return
| 4,752 | Python | .py | 111 | 31.45045 | 119 | 0.634175 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,485 | dial.py | zimolab_PyGUIAdapter/pyguiadapter/widgets/extend/dial.py | import dataclasses
from typing import Type, Optional, Any
from qtpy.QtCore import Qt
from qtpy.QtWidgets import QWidget, QDial, QLabel, QVBoxLayout
from ..common import CommonParameterWidgetConfig, CommonParameterWidget
from ...utils import type_check
@dataclasses.dataclass(frozen=True)
class DialConfig(CommonParameterWidgetConfig):
"""Dial的配置类。"""
default_value: Optional[int] = 0
"""控件的默认值"""
min_value: int = 0
"""最小值"""
max_value: int = 100
"""最大值"""
notch_target: Optional[float] = None
"""缺口之间的目标像素数"""
notches_visible: bool = True
"""是否显示缺口"""
wrapping: bool = False
"""是否循环"""
single_step: int = 1
"""单次调整的步长"""
page_step: Optional[int] = None
"""使用PageUp/PageDown键时调整的步长"""
tracking: bool = True
"""是否跟踪鼠标"""
inverted_controls: bool = False
"""是否启用反转控制"""
inverted_appearance: bool = False
"""是否启用反转外观"""
show_value_label: bool = True
"""是否显示值标签"""
prefix: str = ""
"""值标签的前缀"""
suffix: str = ""
"""值标签的后缀"""
height: Optional[int] = 120
"""控件的高度"""
width: Optional[int] = None
"""控件的宽度"""
@classmethod
def target_widget_class(cls) -> Type["Dial"]:
return Dial
class Dial(CommonParameterWidget):
ConfigClass = DialConfig
def __init__(
self,
parent: Optional[QWidget],
parameter_name: str,
config: DialConfig,
):
self._value_widget: Optional[QWidget] = None
self._dial: Optional[QDial] = None
self._label: Optional[QLabel] = None
super().__init__(parent, parameter_name, config)
@property
def value_widget(self) -> QWidget:
self._config: DialConfig
if self._value_widget is None:
self._value_widget = QWidget(self)
self._dial = QDial(self._value_widget)
if self._config.height:
self._value_widget.setFixedHeight(self._config.height)
if self._config.width:
self._value_widget.setFixedWidth(self._config.width)
layout = QVBoxLayout()
self._value_widget.setLayout(layout)
layout.addWidget(self._dial, 9)
if self._config.show_value_label:
self._label = QLabel(self._value_widget)
layout.addWidget(self._label, 1)
# noinspection PyUnresolvedReferences
self._dial.valueChanged.connect(self._on_value_changed)
self._dial.setOrientation(Qt.Horizontal)
self._dial.setMinimum(self._config.min_value)
self._dial.setMaximum(self._config.max_value)
self._dial.setSingleStep(self._config.single_step)
if self._config.page_step is not None:
self._dial.setPageStep(self._config.page_step)
self._dial.setTracking(self._config.tracking)
self._dial.setInvertedControls(self._config.inverted_controls)
self._dial.setInvertedAppearance(self._config.inverted_appearance)
if self._config.notch_target is not None:
self._dial.setNotchTarget(self._config.notch_target)
self._dial.setNotchesVisible(self._config.notches_visible)
self._dial.setWrapping(self._config.wrapping)
if self._label is not None:
self._label.setAlignment(Qt.AlignVCenter | Qt.AlignHCenter)
self._on_value_changed(self._dial.value())
return self._value_widget
def check_value_type(self, value: Any):
type_check(value, (int,), allow_none=True)
def set_value_to_widget(self, value: Any):
value = int(value)
self._dial.setValue(value)
def get_value_from_widget(self) -> int:
return self._dial.value()
def _on_value_changed(self, value: int):
self._config: DialConfig
if self._label is None:
return
self._label.setText(f"{self._config.prefix}{value}{self._config.suffix}")
| 4,209 | Python | .py | 103 | 30.300971 | 81 | 0.625486 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,486 | slider.py | zimolab_PyGUIAdapter/pyguiadapter/widgets/extend/slider.py | import dataclasses
from typing import Type, Optional, Any
from qtpy.QtCore import Qt
from qtpy.QtWidgets import QWidget, QSlider, QLabel, QVBoxLayout
from ..common import CommonParameterWidgetConfig, CommonParameterWidget
from ...utils import type_check
TickPosition = QSlider.TickPosition
@dataclasses.dataclass(frozen=True)
class SliderConfig(CommonParameterWidgetConfig):
"""Slider的配置类"""
default_value: Optional[int] = 0
"""控件的默认值"""
min_value: int = 0
"""最小值"""
max_value: int = 100
"""最大值"""
single_step: int = 1
"""单次滑动的步长"""
page_step: Optional[int] = None
"""PageUp/PageDown按键按下时调整的步长"""
tick_interval: Optional[int] = None
"""刻度间隔"""
tick_position: TickPosition = TickPosition.TicksBothSides
"""刻度位置"""
tracking: bool = True
"""是否跟踪鼠标"""
inverted_controls: bool = False
"""是否启用反转控制"""
inverted_appearance: bool = False
"""是否显示反转外观"""
show_value_label: bool = True
"""是否显示值标签"""
prefix: str = ""
"""值前缀"""
suffix: str = ""
"""值后缀"""
@classmethod
def target_widget_class(cls) -> Type["Slider"]:
return Slider
class Slider(CommonParameterWidget):
ConfigClass = SliderConfig
NoTicks = TickPosition.NoTicks
"""刻度位置:不显示刻度"""
TickBothSides = TickPosition.TicksBothSides
"""刻度位置:两侧显示刻度"""
TicksAbove = TickPosition.TicksAbove
"""刻度位置:上方显示刻度"""
TicksBelow = TickPosition.TicksBelow
"""刻度位置:下方显示刻度"""
TicksLeft = TickPosition.TicksLeft
"""刻度位置:左侧显示刻度"""
TicksRight = TickPosition.TicksRight
"""刻度位置:右侧显示刻度"""
def __init__(
self,
parent: Optional[QWidget],
parameter_name: str,
config: SliderConfig,
):
self._value_widget: Optional[QWidget] = None
self._slider: Optional[QSlider] = None
self._label: Optional[QLabel] = None
super().__init__(parent, parameter_name, config)
@property
def value_widget(self) -> QWidget:
self._config: SliderConfig
if self._value_widget is None:
self._value_widget = QWidget(self)
self._slider = QSlider(self._value_widget)
layout = QVBoxLayout()
self._value_widget.setLayout(layout)
layout.addWidget(self._slider)
if self._config.show_value_label:
self._label = QLabel(self._value_widget)
layout.addWidget(self._label)
# noinspection PyUnresolvedReferences
self._slider.valueChanged.connect(self._on_value_changed)
self._slider.setOrientation(Qt.Horizontal)
self._slider.setMinimum(self._config.min_value)
self._slider.setMaximum(self._config.max_value)
self._slider.setSingleStep(self._config.single_step)
if self._config.page_step is not None:
self._slider.setPageStep(self._config.page_step)
if self._config.tick_interval is not None:
self._slider.setTickInterval(self._config.tick_interval)
self._slider.setTickPosition(self._config.tick_position)
self._slider.setTracking(self._config.tracking)
self._slider.setInvertedControls(self._config.inverted_controls)
self._slider.setInvertedAppearance(self._config.inverted_appearance)
if self._label is not None:
self._label.setAlignment(Qt.AlignVCenter | Qt.AlignHCenter)
self._on_value_changed(self._slider.value())
return self._value_widget
def check_value_type(self, value: Any):
type_check(value, (int, bool), allow_none=True)
def set_value_to_widget(self, value: Any):
try:
self._slider.setValue(int(value))
except Exception as e:
raise ValueError(f"not a int: {type(value)}") from e
def get_value_from_widget(self) -> int:
return self._slider.value()
def _on_value_changed(self, value: int):
self._config: SliderConfig
if self._label is None:
return
self._label.setText(f"{self._config.prefix}{value}{self._config.suffix}")
| 4,449 | Python | .py | 107 | 30.869159 | 81 | 0.642804 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,487 | multichoice.py | zimolab_PyGUIAdapter/pyguiadapter/widgets/extend/multichoice.py | import dataclasses
from typing import Type, List, Any, Dict, Optional, Union, Sequence
from qtpy.QtWidgets import QWidget, QGridLayout, QCheckBox, QButtonGroup
from ..common import CommonParameterWidgetConfig, CommonParameterWidget
class _CheckBox(QCheckBox):
def __init__(self, parent: Optional[QWidget], user_data: Any):
super().__init__(parent)
self._user_data = user_data
@property
def user_data(self) -> Any:
return self._user_data
@dataclasses.dataclass(frozen=True)
class MultiChoiceBoxConfig(CommonParameterWidgetConfig):
"""MultiChoiceBox的配置类。"""
default_value: Optional[Sequence[Any]] = dataclasses.field(default_factory=list)
"""默认选中的值"""
choices: Union[Sequence[Any], Dict[str, Any]] = dataclasses.field(
default_factory=list
)
"""可选项列表。为字典时,将键值对的键作为显示文本,键值对的值作为实际的值;否则,对每个选项调用str(),将返回值作为显示文本,选项本身作为实际的值。"""
columns: int = 1
"""选项的列数"""
@classmethod
def target_widget_class(cls) -> Type["MultiChoiceBox"]:
return MultiChoiceBox
class MultiChoiceBox(CommonParameterWidget):
ConfigClass = MultiChoiceBoxConfig
def __init__(
self,
parent: Optional[QWidget],
parameter_name: str,
config: MultiChoiceBoxConfig,
):
self._value_widget: Optional[QWidget] = None
self._button_layout: Optional[QGridLayout] = None
self._button_group: Optional[QButtonGroup] = None
super().__init__(parent, parameter_name, config)
@property
def value_widget(self) -> QWidget:
if self._value_widget is None:
self._value_widget = QWidget(self)
self._button_layout = QGridLayout()
self._button_group = QButtonGroup(self._value_widget)
self._button_group.setExclusive(False)
self._value_widget.setLayout(self._button_layout)
self._add_choices()
return self._value_widget
def set_value_to_widget(self, value: Sequence[Any]):
if not isinstance(value, (list, set, tuple)):
value = [value]
for btn in self._button_group.buttons():
if btn.user_data in value:
btn.setChecked(True)
else:
btn.setChecked(False)
def get_value_from_widget(self) -> List[Any]:
ret = []
for btn in self._button_group.buttons():
if btn.isChecked():
ret.append(btn.user_data)
return ret
def _add_choices(self):
self._config: MultiChoiceBoxConfig
assert isinstance(self._config.choices, (list, tuple, set, dict))
cols = max(self._config.columns, 1)
if isinstance(self._config.choices, (list, tuple, set)):
for idx, choice in enumerate(self._config.choices):
button = _CheckBox(self, choice)
button.setText(str(choice))
self._button_group.addButton(button)
if idx % cols == 0:
self._button_layout.addWidget(button, idx // cols, 0)
else:
self._button_layout.addWidget(button, idx // cols, idx % cols)
return
if isinstance(self._config.choices, dict):
for idx, (key, value) in enumerate(self._config.choices.items()):
button = _CheckBox(self, value)
button.setText(key)
self._button_group.addButton(button)
if idx % cols == 0:
self._button_layout.addWidget(button, idx // cols, 0)
else:
self._button_layout.addWidget(button, idx // cols, idx % cols)
| 3,814 | Python | .py | 84 | 33.47619 | 84 | 0.617232 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,488 | fileselect.py | zimolab_PyGUIAdapter/pyguiadapter/widgets/extend/fileselect.py | import dataclasses
import os
from typing import Type, Any, List, Tuple, Set, Optional, Union, Sequence
from qtpy.QtCore import QMimeData, QUrl
from qtpy.QtWidgets import QWidget
from ._path import PathSelectWidget
from ..common import CommonParameterWidgetConfig, CommonParameterWidget
from ...utils import type_check
@dataclasses.dataclass(frozen=True)
class FileSelectConfig(CommonParameterWidgetConfig):
"""FileSelect的配置类。"""
default_value: Optional[str] = ""
"""默认值"""
placeholder: str = ""
"""占位符文字"""
dialog_title: str = ""
"""文件对话框标题"""
start_dir: str = ""
"""文件对话框起始路径"""
filters: str = ""
"""文件对话框的文件过滤器"""
save_file: bool = False
"""是否为保存文件对话框"""
select_button_text: str = "..."
"""选择按钮文字"""
clear_button: bool = False
"""是否显示清除按钮"""
drag_n_drop: bool = True
"""是否启用文件拖放功能"""
normalize_path: bool = False
"""是否将路径标准化。若设置为True,则在获取路径时,将使用os.path.normpath()函数进行标准化"""
absolutize_path: bool = False
"""是否将路径绝对化。若设置为True,则在获取路径时,将使用os.path.abspath()函数进行绝对化"""
@classmethod
def target_widget_class(cls) -> Type["FileSelect"]:
return FileSelect
class FileSelect(CommonParameterWidget):
ConfigClass = FileSelectConfig
def __init__(
self, parent: Optional[QWidget], parameter_name: str, config: FileSelectConfig
):
self._config: FileSelectConfig
self._value_widget: Optional[PathSelectWidget] = None
super().__init__(parent, parameter_name, config)
@property
def value_widget(self) -> PathSelectWidget:
self._config: FileSelectConfig
if self._value_widget is None:
self._value_widget = PathSelectWidget(
self,
select_directory=False,
open_file=not self._config.save_file,
save_file=self._config.save_file,
multiple_files=False,
select_button_text=self._config.select_button_text,
dialog_title=self._config.dialog_title,
start_dir=self._config.start_dir,
filters=self._config.filters,
placeholder=self._config.placeholder,
clear_button=self._config.clear_button,
)
return self._value_widget
def check_value_type(self, value: Any):
type_check(value, (str,), allow_none=True)
def set_value_to_widget(self, value: Any):
self._config: FileSelectConfig
value = value or ""
value = str(value)
self._value_widget.set_path(value)
def get_value_from_widget(self) -> str:
self._config: FileSelectConfig
value = self._value_widget.get_path()
if self._config.normalize_path:
value = os.path.normpath(value)
if self._config.absolutize_path:
value = os.path.abspath(value)
return value
def on_drag(self, mime_data: QMimeData) -> bool:
if not mime_data.hasUrls():
return False
urls = mime_data.urls()
file_path = urls[0].toLocalFile()
if not file_path:
return False
if not os.path.isfile(file_path):
return False
return True
def on_drop(self, urls: List[QUrl], mime_data: QMimeData):
self._config: FileSelectConfig
if not urls:
return
path = urls[0].toLocalFile()
if self._config.normalize_path:
path = os.path.normpath(path)
if self._config.absolutize_path:
path = os.path.abspath(path)
self._value_widget.set_paths(os.path.abspath(path))
@dataclasses.dataclass(frozen=True)
class MultiFileSelectConfig(CommonParameterWidgetConfig):
"""MultiFileSelect的配置类。"""
default_value: Union[Sequence[str], str, type(None)] = ()
"""默认值"""
placeholder: str = ""
"""占位符文字"""
dialog_title: str = ""
"""文件对话框标题"""
start_dir: str = ""
"""文件对话框起始路径"""
filters: str = ""
"""文件对话框的文件过滤器"""
file_separator: str = ";;"
"""文件分隔符"""
select_button_text: str = "..."
"""选择按钮文字"""
clear_button: bool = False
"""是否显示清除按钮"""
drag_n_drop: bool = True
"""是否启用文件拖放功能"""
normalize_path: bool = False
"""是否将路径标准化。若设置为True,则在获取路径时,将使用os.path.normpath()函数进行标准化"""
absolutize_path: bool = False
"""是否将路径绝对化。若设置为True,则在获取路径时,将使用os.path.abspath()函数进行绝对化"""
@classmethod
def target_widget_class(cls) -> Type["MultiFileSelect"]:
return MultiFileSelect
class MultiFileSelect(CommonParameterWidget):
ConfigClass = MultiFileSelectConfig
def __init__(
self,
parent: Optional[QWidget],
parameter_name: str,
config: MultiFileSelectConfig,
):
self._value_widget: Optional[PathSelectWidget] = None
super().__init__(parent, parameter_name, config)
@property
def value_widget(self) -> PathSelectWidget:
self._config: MultiFileSelectConfig
if self._value_widget is None:
self._value_widget = PathSelectWidget(
self,
select_directory=False,
open_file=True,
save_file=False,
multiple_files=True,
select_button_text=self._config.select_button_text,
dialog_title=self._config.dialog_title,
start_dir=self._config.start_dir,
filters=self._config.filters,
placeholder=self._config.placeholder,
clear_button=self._config.clear_button,
file_separator=self._config.file_separator,
)
return self._value_widget
def check_value_type(self, value: Any):
type_check(value, (str, list, tuple, set), allow_none=True)
def set_value_to_widget(
self, value: Union[str, List[str], Tuple[str, ...], Set[str]]
):
value = value or []
self._value_widget.set_paths(value)
def get_value_from_widget(self) -> List[str]:
return self._value_widget.get_paths()
def _norm_path(self, path: str) -> str:
self._config: MultiFileSelectConfig
if self._config.normalize_path:
return os.path.normpath(path)
if self._config.absolutize_path:
return os.path.abspath(path)
return path
def on_drag(self, mime_data: QMimeData) -> bool:
if not mime_data.hasUrls():
return False
if not mime_data.hasUrls():
return False
return True
def on_drop(self, urls: List[QUrl], mime_data: QMimeData):
self._config: MultiFileSelectConfig
if not urls:
return
paths = [
self._norm_path(f)
for f in (url.toLocalFile() for url in urls)
if os.path.isfile(f)
]
self.set_value(paths)
| 7,399 | Python | .py | 186 | 28.327957 | 86 | 0.615315 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,489 | _path.py | zimolab_PyGUIAdapter/pyguiadapter/widgets/extend/_path.py | from typing import List, Tuple, Set, Optional, Union
from qtpy.QtWidgets import QLineEdit, QToolButton, QWidget, QHBoxLayout
from ... import utils
class PathSelectWidget(QWidget):
DEFAULT_SELECT_BUTTON_TEXT = "..."
DEFAULT_FILE_SEPARATOR = ";;"
def __init__(
self,
parent: Optional[QWidget] = None,
*,
select_directory: bool = False,
open_file: bool = True,
save_file: bool = False,
multiple_files: bool = False,
file_separator: str = DEFAULT_FILE_SEPARATOR,
select_button_text: Optional[str] = None,
select_button_icon: utils.IconType = None,
dialog_title: str = "",
start_dir: str = "",
filters: Optional[str] = None,
placeholder: str = "",
clear_button: bool = False,
):
super().__init__(parent)
self._layout = QHBoxLayout()
self.setLayout(self._layout)
self._layout.setContentsMargins(0, 0, 0, 0)
# self._layout.setSpacing(0)
self._select_directory = select_directory
self._open_file = open_file
self._save_file = save_file
self._multiple_files = multiple_files
self._file_separator = file_separator
self._dialog_title = dialog_title
self._start_dir = start_dir
self._filters = filters
self._path_edit = QLineEdit(self)
if placeholder:
self._path_edit.setPlaceholderText(placeholder)
self._path_edit.setClearButtonEnabled(clear_button)
self._select_button: QToolButton = QToolButton(self)
if not select_button_text:
select_button_text = self.DEFAULT_SELECT_BUTTON_TEXT
self._select_button.setText(select_button_text)
select_button_icon = utils.get_icon(select_button_icon)
if select_button_icon:
self._select_button.setIcon(select_button_icon)
# noinspection PyUnresolvedReferences
self._select_button.clicked.connect(self._on_select_path)
self._layout.addWidget(self._path_edit)
self._layout.addWidget(self._select_button)
def _on_select_path(self):
if self._select_directory:
directory = utils.get_existing_directory(
self, title=self._dialog_title or "", start_dir=self._start_dir or ""
)
if directory:
self._path_edit.setText(directory)
return
if self._save_file:
filename = utils.get_save_file(
self,
title=self._dialog_title or "",
start_dir=self._start_dir or "",
filters=self._filters or "",
)
if filename:
self._path_edit.setText(filename)
return
if self._multiple_files:
assert (
self._file_separator is not None and self._file_separator.strip() != ""
)
filenames = utils.get_open_files(
self,
title=self._dialog_title or "",
start_dir=self._start_dir or "",
filters=self._filters or "",
)
if filenames:
self._path_edit.setText(self._file_separator.join(filenames))
else:
filename = utils.get_open_file(
self,
title=self._dialog_title or "",
start_dir=self._start_dir or "",
filters=self._filters or "",
)
if filename:
self._path_edit.setText(filename)
def set_path(self, p: str):
self._path_edit.setText(p)
def get_path(self) -> str:
return self._path_edit.text()
def set_paths(self, ps: Union[str, List[str], Tuple[str, ...], Set[str]]):
assert self._file_separator is not None and self._file_separator.strip() != ""
if not isinstance(ps, str):
ps = self._file_separator.join(ps)
self._path_edit.setText(ps)
def get_paths(self) -> List[str]:
if not self._file_separator:
return [self.get_path()]
return self._path_edit.text().split(self._file_separator)
| 4,175 | Python | .py | 103 | 29.776699 | 87 | 0.577388 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,490 | floatedit.py | zimolab_PyGUIAdapter/pyguiadapter/widgets/extend/floatedit.py | import dataclasses
from typing import Type, Any, Optional
from qtpy.QtGui import QDoubleValidator
from qtpy.QtWidgets import QWidget, QLineEdit
from ..common import CommonParameterWidgetConfig, CommonParameterWidget
from ...exceptions import ParameterError
from ...utils import type_check
@dataclasses.dataclass(frozen=True)
class FloatLineEditConfig(CommonParameterWidgetConfig):
"""FloatLineEdit的配置类。"""
default_value: Optional[float] = 0.0
"""控件的默认值"""
min_value: float = -2147483648.0
"""最小值"""
max_value: float = 2147483647.0
"""最大值"""
decimals: int = 2
"""小数点后位数"""
scientific_notation: bool = False
"""是否使用科学计数法"""
placeholder: str = ""
"""占位符文本"""
clear_button: bool = False
"""是否显示清除按钮"""
empty_value: Optional[float] = 0.0
"""输入框为空时的默认值,若设置为None则表示不允许输入空值,用户输入空值,获取和设置值时会抛出ParameterError"""
@classmethod
def target_widget_class(cls) -> Type["FloatLineEdit"]:
return FloatLineEdit
class FloatLineEdit(CommonParameterWidget):
ConfigClass = FloatLineEditConfig
def __init__(
self,
parent: Optional[QWidget],
parameter_name: str,
config: FloatLineEditConfig,
):
self._value_widget: Optional[QLineEdit] = None
self._validator: Optional[QDoubleValidator] = None
super().__init__(parent, parameter_name, config)
@property
def value_widget(self) -> QLineEdit:
if self._value_widget is None:
config: FloatLineEditConfig = self.config
self._value_widget = QLineEdit(self)
if config.placeholder:
self._value_widget.setPlaceholderText(config.placeholder)
if config.clear_button:
self._value_widget.setClearButtonEnabled(True)
self._validator = QDoubleValidator(
config.min_value,
config.max_value,
config.decimals,
self._value_widget,
)
if config.scientific_notation:
notation = QDoubleValidator.ScientificNotation
else:
notation = QDoubleValidator.StandardNotation
self._validator.setNotation(notation)
self._value_widget.setValidator(self._validator)
self._value_widget.setText(str(config.empty_value))
return self._value_widget
def check_value_type(self, value: Any):
if value == "":
return
type_check(value, (float, int), allow_none=True)
def set_value_to_widget(self, value: Any):
self._config: FloatLineEditConfig
if value == "":
if self._config.empty_value is None:
raise ParameterError(
parameter_name=self.parameter_name,
message="empty value is not allowed",
)
value = self._config.empty_value
self._value_widget.setText(str(value))
def get_value_from_widget(self) -> float:
self._config: FloatLineEditConfig
value = self._value_widget.text().strip()
if value == "":
if self._config.empty_value is None:
raise ParameterError(
parameter_name=self.parameter_name,
message="empty value is not allowed",
)
return self._config.empty_value
try:
value = float(value)
except Exception as e:
raise ValueError(f"not a float: {e}") from e
else:
return value
| 3,727 | Python | .py | 93 | 28.623656 | 73 | 0.619837 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,491 | dirselect.py | zimolab_PyGUIAdapter/pyguiadapter/widgets/extend/dirselect.py | import dataclasses
from typing import Type, Any, Optional
from qtpy.QtWidgets import QWidget
from ._path import PathSelectWidget
from ..common import CommonParameterWidgetConfig, CommonParameterWidget
from ...utils import type_check
@dataclasses.dataclass(frozen=True)
class DirSelectConfig(CommonParameterWidgetConfig):
"""DirSelect的配置类。"""
default_value: Optional[str] = ""
"""默认值"""
placeholder: str = ""
"""占位符文字"""
start_dir: str = ""
"""起始目录"""
dialog_title: str = ""
"""文件对话框标题"""
select_button_text: str = "..."
"""选择按钮文字"""
clear_button: bool = False
"""是否显示清除按钮"""
@classmethod
def target_widget_class(cls) -> Type["DirSelect"]:
return DirSelect
class DirSelect(CommonParameterWidget):
ConfigClass = DirSelectConfig
def __init__(
self, parent: Optional[QWidget], parameter_name: str, config: DirSelectConfig
):
self._value_widget: Optional[PathSelectWidget] = None
super().__init__(parent, parameter_name, config)
@property
def value_widget(self) -> PathSelectWidget:
self._config: DirSelectConfig
if self._value_widget is None:
self._value_widget = PathSelectWidget(
self,
select_directory=True,
open_file=False,
save_file=False,
multiple_files=False,
select_button_text=self._config.select_button_text,
dialog_title=self._config.dialog_title,
start_dir=self._config.start_dir,
filters=None,
placeholder=self._config.placeholder,
clear_button=self._config.clear_button,
)
return self._value_widget
def check_value_type(self, value: Any):
type_check(value, (str,), allow_none=True)
def set_value_to_widget(self, value: Any):
value = value or ""
self._value_widget.set_path(str(value))
def get_value_from_widget(self) -> str:
return self._value_widget.get_path()
| 2,146 | Python | .py | 56 | 28.857143 | 85 | 0.631764 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,492 | __init__.py | zimolab_PyGUIAdapter/pyguiadapter/widgets/extend/__init__.py | from .choicebox import ChoiceBox, ChoiceBoxConfig
from .multichoice import MultiChoiceBox, MultiChoiceBoxConfig
from .slider import Slider, SliderConfig
from .dial import Dial, DialConfig
from .colorpicker import (
ColorType,
ColorPicker,
ColorPickerConfig,
ColorTuplePicker,
ColorHexPicker,
)
from .keysequenceedit import KeySequenceEdit, KeySequenceEditConfig, KeySequenceFormat
from .stringlist import StringListEdit, StringListEditConfig
from .plaindict import PlainDictEdit, PlainDictEditConfig
from .fileselect import (
FileSelectConfig,
FileSelect,
MultiFileSelectConfig,
MultiFileSelect,
)
from .dirselect import DirSelectConfig, DirSelect
from .intedit import IntLineEditConfig, IntLineEdit
from .floatedit import FloatLineEditConfig, FloatLineEdit
from .jsonedit import JsonEditConfig, JsonEdit
from .textedit import TextEdit, TextEditConfig
__all__ = [
"IntLineEdit",
"IntLineEditConfig",
"FloatLineEditConfig",
"FloatLineEdit",
"JsonEditConfig",
"JsonEdit",
"TextEdit",
"TextEditConfig",
"MultiChoiceBoxConfig",
"MultiChoiceBox",
"ChoiceBox",
"ChoiceBoxConfig",
"Slider",
"SliderConfig",
"Dial",
"DialConfig",
"ColorPicker",
"ColorTuplePicker",
"ColorHexPicker",
"ColorPickerConfig",
"KeySequenceEditConfig",
"KeySequenceEdit",
"KeySequenceFormat",
"StringListEdit",
"StringListEditConfig",
"PlainDictEdit",
"PlainDictEditConfig",
"FileSelect",
"FileSelectConfig",
"DirSelect",
"DirSelectConfig",
"MultiFileSelect",
"MultiFileSelectConfig",
]
| 1,624 | Python | .py | 60 | 23.25 | 86 | 0.762636 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,493 | jsonedit.py | zimolab_PyGUIAdapter/pyguiadapter/widgets/extend/jsonedit.py | import dataclasses
import json
from typing import Type, Any, Optional
from pyqcodeeditor.highlighters import QJSONHighlighter
from qtpy.QtWidgets import QWidget
from ..basic.base import BaseCodeEdit, BaseCodeEditConfig, StandaloneCodeEditorConfig
from ...codeeditor import JsonFormatter
JSON_FILE_FILTERS = (
"JSON files (*.json);;Text files(*.txt);;Text files(*.text);;All files (*.*)"
)
@dataclasses.dataclass(frozen=True)
class JsonEditConfig(BaseCodeEditConfig):
"""JsonEdit的配置类。"""
default_value: Optional[Any] = dataclasses.field(default_factory=set)
"""控件的默认值"""
height: Optional[int] = 230
"""inplace编辑器的高度"""
width: Optional[int] = None
"""inplace编辑器的宽度"""
standalone_editor: bool = True
"""是否启用独立(standalone)代码编辑器"""
standalone_editor_button: bool = "Edit Json"
"""standalone编辑器启动按钮文本"""
standalone_editor_config: StandaloneCodeEditorConfig = dataclasses.field(
default_factory=StandaloneCodeEditorConfig
)
"""standalone编辑器配置"""
indent_size: int = 2
"""json格式化缩进大小"""
initial_text: str = "{}"
highlighter: Type[QJSONHighlighter] = QJSONHighlighter
formatter: JsonFormatter = dataclasses.field(default_factory=JsonFormatter)
@classmethod
def target_widget_class(cls) -> Type["JsonEdit"]:
return JsonEdit
class JsonEdit(BaseCodeEdit):
ConfigClass = JsonEditConfig
def __init__(
self,
parent: Optional[QWidget],
parameter_name: str,
config: JsonEditConfig,
):
super().__init__(parent, parameter_name, config)
def _get_data(self, text: str) -> Any:
try:
return json.loads(text)
except Exception as e:
raise ValueError(f"not a json str: {e}") from e
def _set_data(self, data: Any) -> str:
config: JsonEditConfig = self.config
try:
return json.dumps(data, ensure_ascii=False, indent=config.indent_size)
except Exception as e:
raise ValueError(f"not a json object: {e}") from e
| 2,167 | Python | .py | 55 | 31.381818 | 85 | 0.687563 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,494 | keysequenceedit.py | zimolab_PyGUIAdapter/pyguiadapter/widgets/extend/keysequenceedit.py | import dataclasses
from typing import Type, Union, Optional, Any, Literal, List
from qtpy.QtGui import QKeySequence
from qtpy.QtWidgets import QWidget, QKeySequenceEdit
from ..common import CommonParameterWidgetConfig, CommonParameterWidget
from ...utils import type_check
KeySequenceFormat = QKeySequence.SequenceFormat
@dataclasses.dataclass(frozen=True)
class KeySequenceEditConfig(CommonParameterWidgetConfig):
"""KeySequenceEdit的配置类。"""
default_value: Union[str, QKeySequence, None] = ""
"""控件的默认值"""
key_sequence_format: KeySequenceFormat = QKeySequence.PortableText
"""按键序列格式"""
return_type: Literal["str", "list"] = "str"
"""返回值类型"""
@classmethod
def target_widget_class(cls) -> Type["KeySequenceEdit"]:
return KeySequenceEdit
class KeySequenceEdit(CommonParameterWidget):
ConfigClass = KeySequenceEditConfig
PortableText = QKeySequence.PortableText
"""按键序列格式:PortableText"""
NativeText = QKeySequence.NativeText
"""按键序列格式:NativeText"""
def __init__(
self,
parent: Optional[QWidget],
parameter_name: str,
config: KeySequenceEditConfig,
):
self._value_widget: Optional[QKeySequenceEdit] = None
super().__init__(parent, parameter_name, config)
@property
def value_widget(self) -> QKeySequenceEdit:
if self._value_widget is None:
self._value_widget = QKeySequenceEdit(self)
return self._value_widget
def check_value_type(self, value: Any):
type_check(value, (str, QKeySequence), allow_none=True)
def set_value_to_widget(self, value: Union[str, QKeySequence]):
self._config: KeySequenceEditConfig
if isinstance(value, str):
value = QKeySequence(value, self._config.key_sequence_format)
self._value_widget.setKeySequence(value)
def get_value_from_widget(self) -> Union[str, List[str]]:
self._config: KeySequenceEditConfig
key_sequence = self._value_widget.keySequence()
if self._config.return_type == "str":
return key_sequence.toString(self._config.key_sequence_format)
else:
return self.split_key_sequences(
key_sequence.toString(self._config.key_sequence_format)
)
@staticmethod
def split_key_sequences(key_sequences: str) -> list:
"""
将一组按键序列字符串分割成单个按键序列组成的列表。
比如:
"Ctrl+Alt+A, Ctrl+B, Ctrl+C" -> ["Ctrl+Alt+A", "Ctrl+B", "Ctrl+C"]
又比如:
"Ctrl+A, Ctrl+B, ,, Ctrl+,, B, C" -> ["Ctrl+A", "Ctrl+B", "Ctrl+,", ",", "B", "C"]
Args:
key_sequences: 按键序列字符串
Returns:
按键序列组成的列表
"""
return [seq.strip() for seq in key_sequences.split(", ") if seq.strip() != ""]
| 2,959 | Python | .py | 68 | 33.676471 | 90 | 0.661601 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,495 | textedit.py | zimolab_PyGUIAdapter/pyguiadapter/widgets/extend/textedit.py | import dataclasses
from typing import Type, Any, Optional
from qtpy.QtGui import QTextOption
from qtpy.QtWidgets import QWidget, QTextEdit
from ..common import CommonParameterWidget, CommonParameterWidgetConfig
from ...utils import type_check
LineWrapMode = QTextEdit.LineWrapMode
AutoFormatting = QTextEdit.AutoFormattingFlag
WrapMode = QTextOption.WrapMode
@dataclasses.dataclass(frozen=True)
class TextEditConfig(CommonParameterWidgetConfig):
"""TextEdit的配置类"""
default_value: Optional[str] = ""
"""控件的默认值"""
placeholder: str = ""
"""控件的占位符"""
accept_rich_text: bool = False
"""是否接受富文本"""
auto_formatting: Optional[AutoFormatting] = None
"""是否自动格式化"""
line_wrap_mode: LineWrapMode = LineWrapMode.WidgetWidth
"""自动换行模式"""
line_wrap_width: int = 88
"""自动换行宽度"""
word_wrap_mode: Optional[WrapMode] = None
"""单词换行模式"""
height: Optional[int] = 200
"""控件高度"""
width: Optional[int] = None
"""控件宽度"""
@classmethod
def target_widget_class(cls) -> Type["TextEdit"]:
return TextEdit
class TextEdit(CommonParameterWidget):
ConfigClass = TextEditConfig
NoLineWrap = LineWrapMode.NoWrap
"""换行模式:不自动换行"""
WidgetWidth = LineWrapMode.WidgetWidth
"""换行模式:根据控件宽度自动换行"""
FixedColumnWidth = LineWrapMode.FixedColumnWidth
"""换行模式:固定列宽换行"""
FixedPixelWidth = LineWrapMode.FixedPixelWidth
"""换行模式:固定像素宽换行"""
NoWordWrap = WrapMode.NoWrap
"""单词换行模式:不换行"""
WordWrap = WrapMode.WordWrap
"""单词换行模式:根据单词自动换行"""
ManualWordWrap = WrapMode.ManualWrap
"""单词换行模式:手动换行"""
WordWrapAnywhere = WrapMode.WrapAnywhere
"""单词换行模式:任意位置换行"""
WordWrapAtWordBoundaryOrAnywhere = WrapMode.WrapAtWordBoundaryOrAnywhere
"""单词换行模式:单词边界或任意位置换行"""
def __init__(
self,
parent: Optional[QWidget],
parameter_name: str,
config: TextEditConfig,
):
self._value_widget: Optional[QTextEdit] = None
super().__init__(parent, parameter_name, config)
@property
def value_widget(self) -> QTextEdit:
self._config: TextEditConfig
if self._value_widget is None:
self._value_widget = QTextEdit(self)
self._value_widget.setPlaceholderText(self._config.placeholder)
self._value_widget.setAcceptRichText(self._config.accept_rich_text)
auto_formatting = self._config.auto_formatting
if auto_formatting is not None:
self._value_widget.setAutoFormatting(auto_formatting)
line_wrap = self._config.line_wrap_mode
if line_wrap is not None:
self._value_widget.setLineWrapMode(line_wrap)
if (
line_wrap == LineWrapMode.FixedColumnWidth
or line_wrap == LineWrapMode.WidgetWidth
) and self._config.line_wrap_width > 0:
self._value_widget.setLineWrapColumnOrWidth(
self._config.line_wrap_width
)
word_wrap = self._config.word_wrap_mode
if word_wrap is not None:
self._value_widget.setWordWrapMode(word_wrap)
if self._config.height is not None and self._config.height > 0:
self._value_widget.setFixedHeight(self._config.height)
if self._config.width is not None and self._config.width > 0:
self._value_widget.setFixedWidth(self._config.width)
return self._value_widget
def check_value_type(self, value: Any):
type_check(value, (str,), allow_none=True)
def set_value_to_widget(self, value: Any):
self.value_widget.setPlainText(str(value))
def get_value_from_widget(self) -> str:
return self._value_widget.toPlainText()
| 4,127 | Python | .py | 95 | 32.010526 | 79 | 0.664385 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,496 | intedit.py | zimolab_PyGUIAdapter/pyguiadapter/widgets/extend/intedit.py | import dataclasses
from qtpy.QtGui import QIntValidator
from qtpy.QtWidgets import QWidget, QLineEdit
from typing import Type, Any, Optional
from ..common import CommonParameterWidgetConfig, CommonParameterWidget
from ...exceptions import ParameterError
from ...utils import type_check
@dataclasses.dataclass(frozen=True)
class IntLineEditConfig(CommonParameterWidgetConfig):
"""IntLineEdit的配置类"""
default_value: Optional[int] = 0
"""控件的默认值"""
placeholder: str = ""
"""输入框的占位符文本"""
clear_button: bool = False
"""是否显示清除按钮"""
min_value: int = -2147483648
"""最小值"""
max_value: int = 2147483647
"""最大值"""
empty_value: Optional[int] = 0
"""输入框为空时的默认值,若设置为None则表示不允许输入空值,用户输入空值,获取和设置值时会抛出ParameterError"""
@classmethod
def target_widget_class(cls) -> Type["IntLineEdit"]:
return IntLineEdit
class IntLineEdit(CommonParameterWidget):
ConfigClass = IntLineEditConfig
def __init__(
self, parent: Optional[QWidget], parameter_name: str, config: IntLineEditConfig
):
self._validator: Optional[QIntValidator] = None
self._value_widget: Optional[QLineEdit] = None
super().__init__(parent, parameter_name, config)
@property
def value_widget(self) -> QLineEdit:
self._config: IntLineEditConfig
if self._value_widget is None:
self._value_widget = QLineEdit(self)
if self._config.placeholder:
self._value_widget.setPlaceholderText(self._config.placeholder)
if self._config.clear_button:
self._value_widget.setClearButtonEnabled(True)
self._validator = QIntValidator(
self._config.min_value, self._config.max_value, self._value_widget
)
self._value_widget.setValidator(self._validator)
self._value_widget.setText(str(self._config.empty_value))
return self._value_widget
def set_value_to_widget(self, value: Any):
self._config: IntLineEditConfig
if value == "":
if self._config.empty_value is None:
raise ParameterError(
parameter_name=self.parameter_name,
message="empty value not allowed",
)
value = self._config.empty_value
self._value_widget.setText(str(value))
def check_value_type(self, value: Any):
if value == "":
return
type_check(value, (int,), allow_none=True)
def get_value_from_widget(self) -> int:
self._config: IntLineEditConfig
value = self._value_widget.text().strip()
if value == "":
if self._config.empty_value is None:
raise ParameterError(
parameter_name=self.parameter_name,
message="empty value not allowed",
)
return self._config.empty_value
try:
value = int(value)
except Exception as e:
raise ValueError(f"not a int: {e}") from e
else:
return value
| 3,245 | Python | .py | 78 | 30.487179 | 87 | 0.629593 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,497 | colorpicker.py | zimolab_PyGUIAdapter/pyguiadapter/widgets/extend/colorpicker.py | import dataclasses
from qtpy.QtCore import Qt
from qtpy.QtGui import QColor, QFont
from qtpy.QtWidgets import QWidget, QLabel, QColorDialog, QFrame
from typing import Type, Tuple, Union, Literal, Optional, Any
from ..common import CommonParameterWidgetConfig, CommonParameterWidget
from ...utils import to_qcolor, get_inverted_color, convert_color, type_check
ColorType = Union[
Tuple[int, int, int, int], # RGB
Tuple[int, int, int], # RGBA
str, # color name or hex
QColor,
list, # will be converted to a tuple
]
class ColorLabel(QLabel):
def __init__(
self,
parent: Optional[QWidget],
alpha_channel: bool = True,
initial_color: ColorType = Qt.white,
display_color_name: bool = True,
):
super().__init__(parent)
self.setAlignment(Qt.AlignCenter)
self.setFrameShape(QFrame.Box)
self.setFrameShadow(QFrame.Raised)
font: QFont = self.font()
font.setBold(True)
self.setFont(font)
self._color = initial_color
self._alpha_channel = alpha_channel
self._display_color_name = display_color_name
self.set_color(initial_color)
def set_color(self, color: ColorType):
if isinstance(color, list):
color = tuple(color)
if isinstance(color, tuple):
if len(color) not in (3, 4):
raise ValueError("color tuple or list must have 3 or 4 elements")
if not isinstance(color, (tuple, QColor, str)):
raise ValueError(f"invalid color type: {type(color)}")
self._color = self.normalize_color(color)
self._update_ui()
def get_color(self) -> QColor:
return self._color
def mouseReleaseEvent(self, ev):
self._pick_color()
super().mouseReleaseEvent(ev)
def _pick_color(self):
if self._alpha_channel:
color = QColorDialog.getColor(
self._color, self, options=QColorDialog.ShowAlphaChannel
)
else:
color = QColorDialog.getColor(self._color, self)
if color.isValid():
self.set_color(color)
def _update_ui(self):
css = "ColorLabel{\n#props\n}"
props = f"background-color: {self._color.name()};\n"
if self._display_color_name:
text_color = get_inverted_color(self._color)
text_color.setAlpha(255)
props += f"color: {text_color.name()};"
display_text = convert_color(self._color, "str", self._alpha_channel)
self.setText(display_text)
self.setStyleSheet(css.replace("#props", props))
@classmethod
def normalize_color(cls, color: ColorType) -> QColor:
return to_qcolor(color)
@dataclasses.dataclass(frozen=True)
class ColorPickerConfig(CommonParameterWidgetConfig):
"""ColorPicker的配置类"""
default_value: Optional[ColorType] = "white"
"""默认颜色值,可以为颜色名称,RGB(或RGBA)字符串,QColor,或颜色元组(列表)"""
initial_color: ColorType = "white"
alpha_channel: bool = True
"""是否显示Alpha通道"""
display_color_name: bool = True
"""颜色标签上是否显示颜色名称"""
width: Optional[int] = None
"""颜色标签的宽度"""
height: Optional[int] = 45
"""颜色标签的高度"""
return_type: Literal["tuple", "QColor", "str"] = "tuple"
"""返回值类型,即从控件获取值时得到的值的类型,可以为“tuple”(返回RGB或RGBA元组),“QColor”(返回QColor对象),
或“str”(返回RGB或RGBA十六进制字符串)"""
@classmethod
def target_widget_class(cls) -> Type["ColorPicker"]:
return ColorPicker
class ColorPicker(CommonParameterWidget):
ConfigClass = ColorPickerConfig
def __init__(
self,
parent: Optional[QWidget],
parameter_name: str,
config: ColorPickerConfig,
):
self._value_widget: Optional[ColorLabel] = None
super().__init__(parent, parameter_name, config)
def check_value_type(self, value: Any):
if isinstance(value, (list, tuple)):
if len(value) in (3, 4):
return
else:
raise ValueError("color tuple or list must have 3 or 4 elements")
type_check(value, (QColor, str), allow_none=True)
@property
def value_widget(self) -> QLabel:
self._config: ColorPickerConfig
if self._value_widget is None:
self._value_widget = ColorLabel(
self,
self._config.alpha_channel,
self._config.initial_color,
self._config.display_color_name,
)
if self._config.width is not None:
self._value_widget.setFixedWidth(self._config.width)
if self._config.height is not None:
self._value_widget.setFixedHeight(self._config.height)
return self._value_widget
def set_value_to_widget(self, value: ColorType):
self._value_widget.set_color(value)
def get_value_from_widget(self) -> ColorType:
self._config: ColorPickerConfig
color = self._value_widget.get_color()
return convert_color(
color, self._config.return_type, self._config.alpha_channel
)
class ColorTuplePicker(ColorPicker):
ConfigClass = ColorPickerConfig
def __init__(
self,
parent: Optional[QWidget],
parameter_name: str,
config: ColorPickerConfig,
):
config = dataclasses.replace(config, return_type="tuple")
super().__init__(parent, parameter_name, config)
class ColorHexPicker(ColorPicker):
ConfigClass = ColorPickerConfig
def __init__(
self,
parent: Optional[QWidget],
parameter_name: str,
config: ColorPickerConfig,
):
config = dataclasses.replace(config, return_type="str")
super().__init__(parent, parameter_name, config)
| 6,033 | Python | .py | 150 | 30.206667 | 81 | 0.630392 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,498 | plaindict.py | zimolab_PyGUIAdapter/pyguiadapter/widgets/extend/plaindict.py | import dataclasses
import json
from collections import OrderedDict
from typing import Type, Dict, Any, List, Tuple, Optional
from pyqcodeeditor.QCodeEditor import QCodeEditor
from pyqcodeeditor.highlighters import QJSONHighlighter
from qtpy.QtCore import Qt, QModelIndex
from qtpy.QtGui import QStandardItemModel, QStandardItem
from qtpy.QtWidgets import (
QWidget,
QTableView,
QGridLayout,
QVBoxLayout,
QPushButton,
QHeaderView,
QDialog,
QDialogButtonBox,
QLineEdit,
QLabel,
)
from ..common import CommonParameterWidgetConfig, CommonParameterWidget
from ... import utils
from ...codeeditor import JsonFormatter
from ...utils import type_check
TextElideMode = Qt.TextElideMode
GridStyle = Qt.PenStyle
@dataclasses.dataclass(frozen=True)
class PlainDictEditConfig(CommonParameterWidgetConfig):
"""PlainDictEdit的配置类"""
default_value: Optional[Dict[str, Any]] = dataclasses.field(default_factory=dict)
"""默认值"""
edit_button_text: str = "Edit"
"""编辑按钮文本"""
add_button_text: str = "Add"
"""添加按钮文本"""
remove_button_text: str = "Remove"
"""移除按钮文本"""
clear_button_text: str = "Clear"
"""清空按钮文本"""
key_header: str = "Key"
"""键值对中键的表头文本"""
value_header: str = "Value"
"""键值对中值的表头文本"""
show_grid: bool = True
"""是否显示网格线"""
grid_style: GridStyle = GridStyle.SolidLine
"""网格线样式"""
alternating_row_colors: bool = True
"""是否交替显示行颜色"""
text_elide_mode: TextElideMode = TextElideMode.ElideRight
"""文本省略模式"""
corner_button_enabled: bool = True
"""是否显示边角按钮"""
vertical_header_visible: bool = False
"""是否显示垂直表头"""
horizontal_header_visible: bool = True
"""是否显示水平表头"""
min_height: int = 260
confirm_remove: bool = True
"""是否在移除数据时弹出确认对话框"""
warning_dialog_title: str = "Warning"
"""警告对话框标题"""
confirm_dialog_title: str = "Confirm"
"""确认对话框标题"""
no_items_message: str = "No item has been added!"
"""没有添加项时的提示信息"""
no_selection_message: str = "No item selected!"
"""没有选择项时的提示信息"""
confirm_remove_message: str = "Are you sure to remove the selected item(s)?"
"""移除项时的确认对话框信息"""
confirm_clear_message: str = "Are you sure to clear all items?"
"""清空项时的确认对话框信息"""
edit_item_title: str = "Edit - {}"
"""编辑项对话框标题,{}将被替换为当前项的键"""
add_item_title: str = "Add Item"
"""添加项对话框标题"""
editor_size: Tuple[int, int] = (500, 400)
"""编辑/添加项对话框大小"""
width: Optional[int] = None
"""表格最小宽度"""
height: Optional[int] = 200
"""表格最小高度"""
@classmethod
def target_widget_class(cls) -> Type["PlainDictEdit"]:
return PlainDictEdit
class PlainDictEdit(CommonParameterWidget):
ConfigClass = PlainDictEditConfig
def __init__(
self,
parent: Optional[QWidget],
parameter_name: str,
config: PlainDictEditConfig,
):
self._value_widget: Optional[QWidget] = None
self._table_view: Optional[QTableView] = None
self._add_button: Optional[QPushButton] = None
self._remove_button: Optional[QPushButton] = None
self._clear_button: Optional[QPushButton] = None
self._edit_button: Optional[QPushButton] = None
self._model: Optional[QStandardItemModel] = None
super().__init__(parent, parameter_name, config)
@property
def value_widget(self) -> QWidget:
self._config: PlainDictEditConfig
if self._value_widget is None:
self._value_widget = QWidget(self)
layout_main = QVBoxLayout()
layout_main.setContentsMargins(0, 0, 0, 0)
layout_main.setSpacing(2)
self._value_widget.setLayout(layout_main)
self._table_view = QTableView(self._value_widget)
if self._config.height is not None and self._config.height > 0:
self._table_view.setMinimumHeight(self._config.height)
if self._config.width is not None and self._config.width > 0:
self._table_view.setMinimumWidth(self._config.width)
self._table_view.setSortingEnabled(False)
self._table_view.setDragEnabled(False)
self._table_view.setTextElideMode(self._config.text_elide_mode)
self._table_view.setAlternatingRowColors(
self._config.alternating_row_colors
)
self._table_view.setShowGrid(self._config.show_grid)
self._table_view.setGridStyle(self._config.grid_style)
self._table_view.setCornerButtonEnabled(self._config.corner_button_enabled)
self._table_view.verticalHeader().setVisible(
self._config.vertical_header_visible
)
self._table_view.horizontalHeader().setVisible(
self._config.horizontal_header_visible
)
self._table_view.horizontalHeader().setSectionResizeMode(
QHeaderView.ResizeToContents
)
self._table_view.horizontalHeader().setStretchLastSection(True)
self._table_view.setEditTriggers(QTableView.NoEditTriggers)
self._table_view.setSelectionBehavior(QTableView.SelectRows)
self._table_view.setSelectionMode(QTableView.SingleSelection)
# noinspection PyUnresolvedReferences
self._table_view.doubleClicked.connect(self._on_start_editing)
self._model = QStandardItemModel(0, 2)
self._model.setHorizontalHeaderLabels(
[self._config.key_header, self._config.value_header]
)
self._table_view.setModel(self._model)
layout_main.addWidget(self._table_view)
layout_buttons = QGridLayout()
self._edit_button = QPushButton(
self._config.edit_button_text, self._value_widget
)
# noinspection PyUnresolvedReferences
self._edit_button.clicked.connect(self._on_edit_item)
layout_buttons.addWidget(self._edit_button, 1, 1)
self._add_button = QPushButton(
self._config.add_button_text, self._value_widget
)
# noinspection PyUnresolvedReferences
self._add_button.clicked.connect(self._on_add_item)
layout_buttons.addWidget(self._add_button, 1, 0)
self._remove_button = QPushButton(
self._config.remove_button_text, self._value_widget
)
# noinspection PyUnresolvedReferences
self._remove_button.clicked.connect(self._on_remove_item)
layout_buttons.addWidget(self._remove_button, 2, 0)
self._clear_button = QPushButton(
self._config.clear_button_text, self._value_widget
)
# noinspection PyUnresolvedReferences
self._clear_button.clicked.connect(self._on_clear_items)
layout_buttons.addWidget(self._clear_button, 2, 1)
layout_main.addLayout(layout_buttons)
return self._value_widget
def check_value_type(self, value: Any):
type_check(value, (dict, OrderedDict), allow_none=True)
def set_value_to_widget(self, value: Dict[str, Any]):
self._clear_items()
cur_key = ""
try:
for key, value in value.items():
cur_key = key
self._insert_item(key, value, -1)
except Exception as e:
raise ValueError(f"invalid value of key '{cur_key}': {e}") from e
def get_value_from_widget(self) -> Dict[str, Any]:
value = OrderedDict()
cur_key = ""
try:
for row in range(self._model.rowCount()):
key_item = self._model.item(row, 0)
value_item = self._model.item(row, 1)
cur_key = key_item.text()
cur_value = json.loads(value_item.text())
value[cur_key] = cur_value
except Exception as e:
raise ValueError(f"invalid value of key '{cur_key}': {e}") from e
return value
def _on_add_item(self):
self._config: PlainDictEditConfig
keys = self._get_keys()
editor = _KeyValueEditor(
self,
keys,
current_key=None,
current_value=None,
key_label=self._config.key_header,
value_label=self._config.value_header,
window_size=self._config.editor_size,
)
editor.setWindowTitle(self._config.add_item_title)
if editor.exec_() == QDialog.Rejected:
return
new_key = editor.get_current_key()
new_value = editor.get_current_value()
if new_key is None or new_value is None:
return
selected_rows = self._table_view.selectionModel().selectedRows()
if not selected_rows:
selected_row = self._model.rowCount()
else:
selected_row = selected_rows[-1]
if isinstance(selected_row, QModelIndex):
if selected_row.isValid():
selected_row = selected_row.row() + 1
else:
selected_row = self._model.rowCount()
self._model.insertRow(selected_row)
self._model.setItem(selected_row, 0, QStandardItem(new_key))
self._model.setItem(selected_row, 1, QStandardItem(new_value))
def _on_remove_item(self):
self._config: PlainDictEditConfig
selected_rows = self._table_view.selectionModel().selectedRows()
if not selected_rows:
utils.show_warning_message(
self,
title=self._config.warning_dialog_title,
message=self._config.no_selection_message,
)
return
if self._config.confirm_remove:
ret = utils.show_question_message(
self,
title=self._config.confirm_dialog_title,
message=self._config.confirm_remove_message,
buttons=utils.StandardButton.Yes | utils.StandardButton.No,
)
if ret != utils.StandardButton.Yes:
return
self._remove_rows(selected_rows)
def _on_edit_item(self):
self._config: PlainDictEditConfig
selected_index = self._table_view.selectionModel().selectedIndexes()
if not selected_index:
utils.show_warning_message(
self,
title=self._config.warning_dialog_title,
message=self._config.no_selection_message,
)
return
first_idx = selected_index[0]
self._on_start_editing(first_idx)
def _on_start_editing(self, idx: QModelIndex):
self._config: PlainDictEditConfig
if not idx.isValid():
return
current_key_item = self._model.item(idx.row(), 0)
current_value_item = self._model.item(idx.row(), 1)
current_key = current_key_item.text()
current_value = current_value_item.text()
keys = self._get_keys()
editor = _KeyValueEditor(
self,
keys,
current_key,
current_value,
key_label=self._config.key_header,
value_label=self._config.value_header,
window_size=self._config.editor_size,
)
editor.setWindowTitle(self._config.edit_item_title.format(current_key))
if editor.exec_() == QDialog.Rejected:
return
new_key = editor.get_current_key()
new_value = editor.get_current_value()
if new_key is None or new_value is None:
return
self._model.setItem(idx.row(), 0, QStandardItem(new_key))
self._model.setItem(idx.row(), 1, QStandardItem(new_value))
def _on_clear_items(self):
self._config: PlainDictEditConfig
if self._item_count() <= 0:
utils.show_info_message(
self,
title=self._config.warning_dialog_title,
message=self._config.no_items_message,
)
return
if not self._config.confirm_remove:
self._clear_items()
return
ret = utils.show_question_message(
self,
title=self._config.confirm_dialog_title,
message=self._config.confirm_clear_message,
buttons=utils.StandardButton.Yes | utils.StandardButton.No,
)
if ret == utils.StandardButton.Yes:
self._clear_items()
def _clear_items(self):
self._model.removeRows(0, self._model.rowCount())
def _insert_item(self, key: str, value: Any, row: int):
try:
value = json.dumps(value, ensure_ascii=False)
except Exception as e:
raise e
else:
if row == -1:
row = self._model.rowCount()
self._model.insertRow(row)
key_item = QStandardItem(key)
value_item = QStandardItem(value)
self._model.setItem(row, 0, key_item)
self._model.setItem(row, 1, value_item)
def _item_count(self) -> int:
return self._model.rowCount()
def _remove_rows(self, rows: List[QModelIndex]):
rows = list(set(row.row() for row in rows if row.isValid()))
if not rows:
return
rows.sort(reverse=True)
for row in rows:
self._model.removeRow(row)
def _get_keys(self) -> List[str]:
keys = []
for i in range(self._item_count()):
key_item = self._model.item(i, 0)
if key_item:
keys.append(key_item.text())
return keys
class _KeyValueEditor(QDialog):
def __init__(
self,
parent: Optional[QWidget],
added_keys: List[str],
current_key: Optional[str] = None,
current_value: Optional[str] = None,
*,
key_label: str = "Key",
value_label: str = "Value",
window_size: Optional[Tuple[int, int]] = None,
):
super().__init__(parent)
self._keys = added_keys
self._current_key = current_key
self._current_value = current_value
self._formater = JsonFormatter()
if window_size:
self.resize(*window_size)
layout = QVBoxLayout()
self.setLayout(layout)
self._key_label = QLabel(key_label, self)
layout.addWidget(self._key_label)
self._key_edit: QLineEdit = QLineEdit(self)
layout.addWidget(self._key_edit)
self._value_label: QLabel = QLabel(value_label, self)
layout.addWidget(self._value_label)
self._value_edit: QCodeEditor = QCodeEditor(self)
highlighter = QJSONHighlighter()
self._value_edit.setHighlighter(highlighter)
layout.addWidget(self._value_edit)
self._button_box = QDialogButtonBox(self)
self._button_box.setStandardButtons(
QDialogButtonBox.Yes | QDialogButtonBox.Cancel
)
self._button_box.setOrientation(Qt.Horizontal)
# noinspection PyUnresolvedReferences
self._button_box.accepted.connect(self._on_confirm)
# noinspection PyUnresolvedReferences
self._button_box.rejected.connect(self._on_cancel)
layout.addWidget(self._button_box)
if self._current_key is not None:
self._key_edit.setText(self._current_key)
if self._current_value is not None:
self._value_edit.setPlainText(
self._formater.format_code(self._current_value)
)
def get_current_key(self) -> Optional[str]:
return self._current_key
def get_current_value(self) -> str:
return self._current_value
def _on_confirm(self):
current_key = self._key_edit.text()
current_value = self._value_edit.toPlainText()
if current_key != self._current_key and current_key in self._keys:
utils.show_warning_message(
self, message=f"Duplicated key: '{current_key}'!"
)
return
if current_value == "":
self._current_value = "null"
self._current_key = current_key
self.accept()
return
try:
current_value = json.dumps(json.loads(current_value), ensure_ascii=False)
except Exception as e:
utils.show_critical_message(self, message=f"json error: {e}")
else:
self._current_value = current_value
self._current_key = current_key
self.accept()
def _on_cancel(self):
self.reject()
| 17,063 | Python | .py | 412 | 30.342233 | 87 | 0.607406 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,499 | typenames.py | zimolab_PyGUIAdapter/pyguiadapter/parser/typenames.py | import re
import typing
from collections.abc import Mapping, MutableMapping, MutableSet, Set
from .. import utils
TYPE_INT = "int"
TYPE_FLOAT = "float"
TYPE_STR = "str"
TYPE_BOOL = "bool"
TYPE_DICT = "dict"
TYPE_LIST = "list"
TYPE_SET = "set"
TYPE_TUPLE = "tuple"
TYPE_ANY = "any"
TYPE_OBJECT = "object"
TYPE_MAPPING = "Mapping"
TYPE_MUTABLE_MAPPING = "MutableMapping"
TYPE_MUTABLE_SET = "MutableSet"
TYPING_ANY = "Any"
TYPING_LITERAL = "Literal"
TYPING_SET = "Set"
TYPING_TUPLE = "Tuple"
TYPING_LIST = "List"
TYPING_DICT = "Dict"
TYPING_UNION = "Union"
TYPING_TYPED_DICT = "TypedDict"
_TYPE_ANN_PATTERN = r"(\w+)\[\s*([\w\W]+)\s*\]"
BasicTypeMap = {
int: TYPE_INT,
float: TYPE_FLOAT,
str: TYPE_STR,
bool: TYPE_BOOL,
dict: TYPE_DICT,
list: TYPE_LIST,
set: TYPE_SET,
tuple: TYPE_TUPLE,
object: TYPE_OBJECT,
any: TYPE_ANY,
Mapping: TYPE_MAPPING,
MutableMapping: TYPE_MUTABLE_MAPPING,
MutableSet: TYPE_MUTABLE_SET,
Set: TYPE_SET,
typing.Any: TYPING_ANY,
typing.Union: TYPING_UNION,
typing.Literal: TYPING_LITERAL,
typing.Dict: TYPING_DICT,
typing.Mapping: TYPE_MAPPING,
typing.MutableMapping: TYPE_MUTABLE_MAPPING,
typing.Set: TYPING_SET,
typing.MutableSet: TYPE_MUTABLE_SET,
typing.Tuple: TYPING_TUPLE,
typing.List: TYPING_LIST,
typing.TypedDict: TYPING_TYPED_DICT,
}
ExtendTypeMap = {
typing.TypedDict: TYPING_TYPED_DICT,
typing.Union: TYPING_UNION,
}
def _get_typename_from_str_annotation(typ: str) -> str:
match = re.match(_TYPE_ANN_PATTERN, typ)
if match is not None:
return match.group(1)
return typ
def _get_type_args_from_str_annotation(typ: str) -> typing.List[str]:
match = re.match(_TYPE_ANN_PATTERN, typ)
if match is not None:
type_arg_str = match.group(2)
return utils.get_type_args(type_arg_str.strip())
return []
def _get_extend_typename(typ: typing.Any) -> str:
if isinstance(typ, type) or getattr(typ, "__name__", None) is not None:
return typ.__name__
return type(typ).__name__
def get_typename(typ: typing.Any) -> str:
if isinstance(typ, str):
typ = typ.strip()
return _get_typename_from_str_annotation(typ)
if not utils.hashable(typ):
return _get_extend_typename(typ)
typename = BasicTypeMap.get(typ, None)
if typename is not None:
return typename
origin_typ = typing.get_origin(typ)
typename = BasicTypeMap.get(origin_typ, None)
if typename is not None:
return typename
typename = ExtendTypeMap.get(origin_typ, None)
if typename is not None:
return typename
return _get_extend_typename(typ)
def get_type_args(typ: typing.Any) -> typing.List[typing.Any]:
if isinstance(typ, str):
typ = typ.strip()
return _get_type_args_from_str_annotation(typ)
args = []
for arg in typing.get_args(typ):
if isinstance(arg, (int, float, str, bool, dict, list, set, tuple)):
args.append(arg)
else:
args.append(get_typename(arg))
return args
| 3,094 | Python | .py | 100 | 26.4 | 76 | 0.672948 | zimolab/PyGUIAdapter | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.