Examples¶
This section provides comprehensive examples showing how to use vibegui in different scenarios.
Basic Examples¶
Simple Form¶
Here’s a simple contact form example:
1"""Simple contact form example."""
2from vibegui import GuiBuilder
3from qtpy.QtWidgets import QApplication
4import sys
5import os
6
7config = {
8 "window": {
9 "title": "Contact Form",
10 "width": 400,
11 "height": 350
12 },
13 "fields": [
14 {
15 "name": "name",
16 "label": "Full Name",
17 "type": "text",
18 "required": True,
19 "placeholder": "Enter your full name"
20 },
21 {
22 "name": "email",
23 "label": "Email",
24 "type": "email",
25 "required": True,
26 "placeholder": "your.email@example.com"
27 },
28 {
29 "name": "phone",
30 "label": "Phone Number",
31 "type": "text",
32 "placeholder": "+1 (555) 123-4567"
33 },
34 {
35 "name": "message",
36 "label": "Message",
37 "type": "textarea",
38 "required": True,
39 "placeholder": "Enter your message here..."
40 }
41 ],
42 "submit_button": True,
43 "submit_label": "Send Message",
44 "cancel_button": True
45}
46
47def handle_submit(data):
48 print("Contact form submitted:")
49 for key, value in data.items():
50 print(f" {key}: {value}")
51
52
53if __name__ == "__main__":
54 app = QApplication(sys.argv)
55 gui = GuiBuilder(config_dict=config, backend='qt')
56 gui.set_submit_callback(handle_submit)
57 gui.show()
58
59 sys.exit(app.exec())
Advanced Form with Validation¶
1"""Advanced form with validation example."""
2from vibegui import GuiBuilder
3from qtpy.QtWidgets import QApplication
4import sys
5import os
6
7config = {
8 "window": {
9 "title": "User Registration",
10 "width": 500,
11 "height": 600
12 },
13 "fields": [
14 {
15 "name": "username",
16 "label": "Username",
17 "type": "text",
18 "required": True,
19 "placeholder": "Choose a username",
20 "tooltip": "Username must be unique"
21 },
22 {
23 "name": "password",
24 "label": "Password",
25 "type": "password",
26 "required": True,
27 "tooltip": "Password must be at least 8 characters"
28 },
29 {
30 "name": "confirm_password",
31 "label": "Confirm Password",
32 "type": "password",
33 "required": True
34 },
35 {
36 "name": "email",
37 "label": "Email Address",
38 "type": "email",
39 "required": True
40 },
41 {
42 "name": "age",
43 "label": "Age",
44 "type": "number",
45 "min_value": 13,
46 "max_value": 120,
47 "required": True
48 },
49 {
50 "name": "country",
51 "label": "Country",
52 "type": "select",
53 "options": ["USA", "Canada", "UK", "Australia", "Germany", "France"],
54 "required": True
55 },
56 {
57 "name": "birthdate",
58 "label": "Birth Date",
59 "type": "date",
60 "required": True
61 },
62 {
63 "name": "terms",
64 "label": "I agree to the terms and conditions",
65 "type": "checkbox",
66 "required": True
67 }
68 ],
69 "submit_button": True,
70 "submit_label": "Register",
71 "cancel_button": True
72}
73
74def validate_registration(data):
75 # Custom validation
76 if data.get('password') != data.get('confirm_password'):
77 print("Error: Passwords do not match")
78 return False
79
80 if len(data.get('password', '')) < 8:
81 print("Error: Password must be at least 8 characters")
82 return False
83
84 return True
85
86def handle_registration(data):
87 if validate_registration(data):
88 print("Registration successful!")
89 print(f"Welcome, {data['username']}!")
90 else:
91 print("Registration failed. Please check your inputs.")
92
93if __name__ == "__main__":
94 app = QApplication(sys.argv)
95 gui = GuiBuilder(config_dict=config, backend='qt')
96 gui.set_submit_callback(handle_registration)
97 gui.show()
98
99 sys.exit(app.exec())
Tabbed Interface Example¶
1"""Tabbed interface example."""
2from vibegui import GuiBuilder
3from qtpy.QtWidgets import QApplication
4import sys
5import os
6
7config = {
8 "window": {
9 "title": "Employee Management",
10 "width": 600,
11 "height": 500
12 },
13 "fields": [
14 # Personal Information fields
15 {"name": "first_name", "label": "First Name", "type": "text", "required": True},
16 {"name": "last_name", "label": "Last Name", "type": "text", "required": True},
17 {"name": "employee_id", "label": "Employee ID", "type": "text", "required": True},
18 {"name": "department", "label": "Department", "type": "select",
19 "options": ["Engineering", "Sales", "Marketing", "HR", "Finance"]},
20 {"name": "hire_date", "label": "Hire Date", "type": "date", "required": True},
21 # Contact Details fields
22 {"name": "email", "label": "Work Email", "type": "email", "required": True},
23 {"name": "phone", "label": "Phone Number", "type": "text"},
24 {"name": "emergency_contact", "label": "Emergency Contact", "type": "text"},
25 {"name": "address", "label": "Address", "type": "textarea"},
26 # Job Details fields
27 {"name": "position", "label": "Position", "type": "text", "required": True},
28 {"name": "salary", "label": "Salary", "type": "number", "min_value": 0},
29 {"name": "full_time", "label": "Full-time Employee", "type": "checkbox", "default_value": True},
30 {"name": "start_time", "label": "Start Time", "type": "time"},
31 {"name": "benefits", "label": "Benefits Package", "type": "select",
32 "options": ["Basic", "Standard", "Premium"]}
33 ],
34 "use_tabs": True,
35 "tabs": [
36 {
37 "name": "personal_info",
38 "title": "Personal Information",
39 "fields": ["first_name", "last_name", "employee_id", "department", "hire_date"]
40 },
41 {
42 "name": "contact_details",
43 "title": "Contact Details",
44 "fields": ["email", "phone", "emergency_contact", "address"]
45 },
46 {
47 "name": "job_details",
48 "title": "Job Details",
49 "fields": ["position", "salary", "full_time", "start_time", "benefits"]
50 }
51 ],
52 "submit_button": True,
53 "submit_label": "Save Employee",
54 "cancel_button": True
55}
56
57if __name__ == "__main__":
58 app = QApplication(sys.argv)
59 gui = GuiBuilder(config_dict=config, backend='qt')
60 gui.show()
61
62 sys.exit(app.exec())
Data Persistence Example¶
1"""Data persistence example."""
2from vibegui import GuiBuilder
3from qtpy.QtWidgets import QApplication
4import sys
5import os
6
7config = {
8 "window": {"title": "Settings Manager", "width": 450, "height": 350},
9 "fields": [
10 {"name": "theme", "label": "Theme", "type": "select",
11 "options": ["Light", "Dark", "Auto"], "default_value": "Auto"},
12 {"name": "language", "label": "Language", "type": "select",
13 "options": ["English", "Spanish", "French", "German"]},
14 {"name": "auto_save", "label": "Auto-save", "type": "checkbox", "default_value": True},
15 {"name": "backup_interval", "label": "Backup Interval (hours)", "type": "number",
16 "min_value": 1, "max_value": 24, "default_value": 6}
17 ],
18 "custom_buttons": [
19 {"name": "load_settings", "label": "Load Settings"},
20 {"name": "save_settings", "label": "Save Settings"},
21 {"name": "reset_defaults", "label": "Reset to Defaults"}
22 ]
23}
24
25settings_file = "user_settings.json"
26
27def load_settings(button_config, form_data):
28 if os.path.exists(settings_file):
29 if gui.load_data_from_file(settings_file):
30 print("Settings loaded successfully!")
31 else:
32 print("Failed to load settings.")
33 else:
34 print("No saved settings found.")
35
36def save_settings(button_config, form_data):
37 if gui.save_data_to_file(settings_file):
38 print("Settings saved successfully!")
39 else:
40 print("Failed to save settings.")
41
42def reset_defaults(button_config, form_data):
43 defaults = {
44 "theme": "Auto",
45 "language": "English",
46 "auto_save": True,
47 "backup_interval": 6
48 }
49 gui.set_form_data(defaults)
50 print("Settings reset to defaults!")
51
52if __name__ == "__main__":
53 app = QApplication(sys.argv)
54 gui = GuiBuilder(config_dict=config, backend='qt')
55 gui.set_custom_button_callback('load_settings', load_settings)
56 gui.set_custom_button_callback('save_settings', save_settings)
57 gui.set_custom_button_callback('reset_defaults', reset_defaults)
58
59 # Auto-load settings on startup
60 if os.path.exists(settings_file):
61 gui.load_data_from_file(settings_file)
62
63 gui.show()
64
65 sys.exit(app.exec())
Field Change Callbacks¶
1"""Field change callbacks example."""
2from vibegui import GuiBuilder
3from qtpy.QtWidgets import QApplication
4import sys
5import os
6
7config = {
8 "window": {"title": "Dynamic Form", "width": 400, "height": 300},
9 "fields": [
10 {"name": "user_type", "label": "User Type", "type": "select",
11 "options": ["Student", "Teacher", "Administrator"], "required": True},
12 {"name": "student_id", "label": "Student ID", "type": "text"},
13 {"name": "grade_level", "label": "Grade Level", "type": "number", "min_value": 1, "max_value": 12},
14 {"name": "department", "label": "Department", "type": "text"},
15 {"name": "admin_level", "label": "Admin Level", "type": "select",
16 "options": ["Level 1", "Level 2", "Level 3"]}
17 ]
18}
19
20def on_user_type_change(field_name, value):
21 print(f"User type changed to: {value}")
22
23 # Enable/disable fields based on user type
24 if value == "Student":
25 gui.set_field_value("student_id", "")
26 gui.set_field_value("grade_level", "")
27 # In a real implementation, you would show/hide fields here
28 print("Showing student-specific fields")
29 elif value == "Teacher":
30 gui.set_field_value("department", "")
31 print("Showing teacher-specific fields")
32 elif value == "Administrator":
33 gui.set_field_value("admin_level", "")
34 print("Showing administrator-specific fields")
35
36if __name__ == "__main__":
37 app = QApplication(sys.argv)
38 gui = GuiBuilder(config_dict=config, backend='qt')
39 gui.add_field_change_callback('user_type', on_user_type_change)
40 gui.show()
41
42 sys.exit(app.exec())
Layout Examples¶
Different layout styles for organizing fields:
1"""Layout examples showing different field organization styles."""
2from vibegui import GuiBuilder
3from qtpy.QtWidgets import QApplication
4import sys
5import os
6
7# Vertical layout (default - stacks fields vertically)
8vertical_config = {
9 "window": {"title": "Vertical Layout", "width": 400, "height": 400},
10 "layout": "vertical",
11 "fields": [
12 {"name": "field1", "label": "Field 1", "type": "text"},
13 {"name": "field2", "label": "Field 2", "type": "text"},
14 {"name": "field3", "label": "Field 3", "type": "number"}
15 ]
16}
17
18# Horizontal layout (arranges fields in a row)
19horizontal_config = {
20 "window": {"title": "Horizontal Layout", "width": 600, "height": 200},
21 "layout": "horizontal",
22 "fields": [
23 {"name": "first", "label": "First", "type": "text"},
24 {"name": "middle", "label": "Middle", "type": "text"},
25 {"name": "last", "label": "Last", "type": "text"}
26 ]
27}
28
29# Grid layout (responsive 2-column grid)
30grid_config = {
31 "window": {"title": "Grid Layout", "width": 600, "height": 400},
32 "layout": "grid",
33 "fields": [
34 {"name": "fname", "label": "First Name", "type": "text"},
35 {"name": "lname", "label": "Last Name", "type": "text"},
36 {"name": "email", "label": "Email", "type": "email"},
37 {"name": "phone", "label": "Phone", "type": "text"},
38 {"name": "city", "label": "City", "type": "text"},
39 {"name": "state", "label": "State", "type": "text"}
40 ]
41}
42
43# Form layout (label-field pairs)
44form_config = {
45 "window": {"title": "Form Layout", "width": 500, "height": 400},
46 "layout": "form",
47 "fields": [
48 {"name": "username", "label": "Username", "type": "text"},
49 {"name": "password", "label": "Password", "type": "password"},
50 {"name": "remember", "label": "Remember me", "type": "checkbox"}
51 ]
52}
53
54# Use different layouts in tabs
55tabbed_layout_config = {
56 "window": {"title": "Mixed Layouts", "width": 600, "height": 500},
57 "fields": [
58 {"name": "v1", "label": "Field 1", "type": "text"},
59 {"name": "v2", "label": "Field 2", "type": "text"},
60 {"name": "g1", "label": "Field 1", "type": "text"},
61 {"name": "g2", "label": "Field 2", "type": "text"},
62 {"name": "g3", "label": "Field 3", "type": "text"},
63 {"name": "g4", "label": "Field 4", "type": "text"}
64 ],
65 "use_tabs": True,
66 "tabs": [
67 {
68 "name": "vertical_tab",
69 "title": "Vertical Tab",
70 "layout": "vertical",
71 "fields": ["v1", "v2"]
72 },
73 {
74 "name": "grid_tab",
75 "title": "Grid Tab",
76 "layout": "grid",
77 "fields": ["g1", "g2", "g3", "g4"]
78 }
79 ]
80}
81
82if __name__ == "__main__":
83 app = QApplication(sys.argv)
84 gui = GuiBuilder(config_dict=grid_config, backend='qt')
85 gui.show()
86
87 sys.exit(app.exec())
Nested Fields Example¶
Using dot notation for hierarchical data structures:
1"""Nested fields example."""
2from vibegui import GuiBuilder
3from qtpy.QtWidgets import QApplication
4import sys
5import json
6import os
7
8config = {
9 "window": {"title": "Application Settings", "width": 600, "height": 500},
10 "layout": "form",
11 "fields": [
12 # Global settings
13 {"name": "global.app_name", "label": "Application Name",
14 "type": "text", "default_value": "My App"},
15 {"name": "global.version", "label": "Version",
16 "type": "text", "default_value": "1.0.0"},
17
18 # Database settings
19 {"name": "database.host", "label": "Database Host",
20 "type": "text", "default_value": "localhost"},
21 {"name": "database.port", "label": "Database Port",
22 "type": "int", "default_value": 5432},
23 {"name": "database.name", "label": "Database Name",
24 "type": "text", "required": True},
25
26 # UI settings
27 {"name": "ui.theme", "label": "Theme",
28 "type": "select", "options": ["light", "dark", "auto"],
29 "default_value": "auto"},
30 {"name": "ui.font_size", "label": "Font Size",
31 "type": "int", "min_value": 8, "max_value": 24, "default_value": 12}
32 ],
33 "submit_button": True
34}
35
36def on_submit(data):
37 print("Settings saved:")
38 print(json.dumps(data, indent=2))
39 # Output will be nested:
40 # {
41 # "global": {"app_name": "...", "version": "..."},
42 # "database": {"host": "...", "port": ..., "name": "..."},
43 # "ui": {"theme": "...", "font_size": ...}
44 # }
45
46if __name__ == "__main__":
47 app = QApplication(sys.argv)
48 gui = GuiBuilder(config_dict=config, backend='qt')
49 gui.set_submit_callback(on_submit)
50 gui.show()
51
52 sys.exit(app.exec())
Float Formatting Example¶
Controlling decimal precision for float fields:
1"""Float formatting example."""
2from vibegui import GuiBuilder
3from qtpy.QtWidgets import QApplication
4import sys
5import os
6
7config = {
8 "window": {"title": "Measurements", "width": 500, "height": 500},
9 "layout": "form",
10 "fields": [
11 {"name": "price", "label": "Price ($)", "type": "float",
12 "format_string": ".2f", "default_value": 99.99},
13
14 {"name": "temperature", "label": "Temperature (°C)", "type": "float",
15 "format_string": ".1f", "default_value": 23.5},
16
17 {"name": "precision", "label": "High Precision", "type": "float",
18 "format_string": ".4f", "default_value": 3.1416},
19
20 {"name": "scientific", "label": "Large Number", "type": "float",
21 "format_string": ".2e", "default_value": 1234567.89},
22
23 {"name": "percentage", "label": "Completion", "type": "float",
24 "format_string": ".1%", "default_value": 0.856},
25
26 {"name": "currency", "label": "Revenue", "type": "float",
27 "format_string": ",.2f", "default_value": 12345.67}
28 ],
29 "submit_button": True
30}
31
32if __name__ == "__main__":
33 app = QApplication(sys.argv)
34 gui = GuiBuilder(config_dict=config, backend='qt')
35 gui.show()
36
37 sys.exit(app.exec())
Loading from JSON Files¶
Create a JSON configuration file:
1{
2 "window": {
3 "title": "My Application",
4 "width": 500,
5 "height": 400
6 },
7 "fields": [
8 {
9 "name": "title",
10 "label": "Title",
11 "type": "select",
12 "options": ["Mr.", "Ms.", "Dr.", "Prof."],
13 "required": true
14 },
15 {
16 "name": "name",
17 "label": "Full Name",
18 "type": "text",
19 "required": true
20 }
21 ],
22 "submit_button": true,
23 "cancel_button": true
24}
Then load it in Python:
1"""JSON configuration loading example."""
2from vibegui import GuiBuilder
3from qtpy.QtWidgets import QApplication
4import sys
5import os
6from pathlib import Path
7
8# Get the path to the example JSON file
9example_json = Path(__file__).parent / "example_config.json"
10
11if __name__ == "__main__":
12 # Load from JSON file
13 app = QApplication(sys.argv)
14 gui = GuiBuilder(config_path=str(example_json), backend='qt')
15 gui.show()
16
17 sys.exit(app.exec())
For more examples, check the examples/ directory in the vibegui repository.