### Run QFluentWidgets Gallery Example Source: https://github.com/zhiyiyo/qfluentwidgets-docs/blob/main/dev/docs/guide/install.md Instructions for navigating to the examples directory and executing the demo script to verify the installation. ```shell cd examples/gallery python demo.py ``` -------------------------------- ### Initialize and Run Local Development Server Source: https://github.com/zhiyiyo/qfluentwidgets-docs/blob/main/README.md Commands to install project dependencies using npm and start the local development server for the documentation site. ```shell cd dev npm install npm run dev ``` -------------------------------- ### Install QFluentWidgets for Qt Frameworks Source: https://github.com/zhiyiyo/qfluentwidgets-docs/blob/main/dev/docs/guide/install.md Commands to install the lite or full versions of QFluentWidgets for PyQt5, PyQt6, PySide2, and PySide6. The full version includes support for advanced features like acrylic components. ```python # lite version pip install PyQt-Fluent-Widgets -i https://pypi.org/simple/ # full version (supports acrylic components) pip install "PyQt-Fluent-Widgets[full]" -i https://pypi.org/simple/ ``` ```python # lite version pip install PyQt6-Fluent-Widgets -i https://pypi.org/simple/ # full version (supports acrylic components) pip install "PyQt6-Fluent-Widgets[full]" -i https://pypi.org/simple/ ``` ```python # lite version pip install PySide2-Fluent-Widgets -i https://pypi.org/simple/ # full version (supports acrylic components) pip install "PySide2-Fluent-Widgets[full]" -i https://pypi.org/simple/ ``` ```python # lite version pip install PySide6-Fluent-Widgets -i https://pypi.org/simple/ # full version (supports acrylic components) pip install "PySide6-Fluent-Widgets[full]" -i https://pypi.org/simple/ ``` -------------------------------- ### FluentWindow Implementation Example Source: https://github.com/zhiyiyo/qfluentwidgets-docs/blob/main/dev/docs/components/window/fluent_window.md A complete example demonstrating how to subclass FluentWindow, define custom widgets, and populate the navigation sidebar with various interfaces. ```python from qfluentwidgets import NavigationItemPosition, FluentWindow, SubtitleLabel, setFont from qfluentwidgets import FluentIcon as FIF class Widget(QFrame): def __init__(self, text: str, parent=None): super().__init__(parent=parent) self.label = SubtitleLabel(text, self) self.hBoxLayout = QHBoxLayout(self) setFont(self.label, 24) self.label.setAlignment(Qt.AlignCenter) self.hBoxLayout.addWidget(self.label, 1, Qt.AlignCenter) self.setObjectName(text.replace(' ', '-')) class Window(FluentWindow): def __init__(self): super().__init__() self.homeInterface = Widget('Home Interface', self) self.initNavigation() self.initWindow() def initNavigation(self): self.addSubInterface(self.homeInterface, FIF.HOME, 'Home') def initWindow(self): self.resize(900, 700) if __name__ == '__main__': app = QApplication(sys.argv) w = Window() w.show() app.exec() ``` -------------------------------- ### Implement MSFluentWindow Layout Source: https://context7.com/zhiyiyo/qfluentwidgets-docs/llms.txt Shows the setup of an MSFluentWindow, a Microsoft Store-style window layout. It includes adding sub-interfaces to the navigation bar and configuring bottom-aligned navigation items. ```python from qfluentwidgets import MSFluentWindow, NavigationItemPosition, FluentIcon as FIF class Window(MSFluentWindow): def __init__(self): super().__init__() self.initNavigation() def initNavigation(self): self.addSubInterface(self.homeInterface, FIF.HOME, 'Home') self.addSubInterface(self.libraryInterface, FIF.BOOK_SHELF, 'Library', FIF.LIBRARY_FILL, NavigationItemPosition.BOTTOM) self.navigationInterface.addItem( routeKey='Help', icon=FIF.HELP, text='Help', onClick=self.showHelp, selectable=False, position=NavigationItemPosition.BOTTOM ) ``` -------------------------------- ### Install QFluentWidgets via pip Source: https://context7.com/zhiyiyo/qfluentwidgets-docs/llms.txt Commands to install the lite or full versions of QFluentWidgets for PyQt5, PyQt6, or PySide6. The full version includes additional features like acrylic components. ```bash # PyQt5 - lite version pip install PyQt-Fluent-Widgets -i https://pypi.org/simple/ # PyQt5 - full version (supports acrylic components) pip install "PyQt-Fluent-Widgets[full]" -i https://pypi.org/simple/ # PyQt6 - lite version pip install PyQt6-Fluent-Widgets -i https://pypi.org/simple/ # PyQt6 - full version pip install "PyQt6-Fluent-Widgets[full]" -i https://pypi.org/simple/ # PySide6 - lite version pip install PySide6-Fluent-Widgets -i https://pypi.org/simple/ # PySide6 - full version pip install "PySide6-Fluent-Widgets[full]" -i https://pypi.org/simple/ ``` -------------------------------- ### Initialize FluentTranslator in QFluentWidgets Source: https://github.com/zhiyiyo/qfluentwidgets-docs/blob/main/dev/docs/guide/i18n.md Demonstrates how to instantiate the FluentTranslator and install it into a PyQt application to enable automatic translation of built-in components. ```python from qfluentwidgets import CalendarPicker, FluentTranslator app = QApplication(sys.argv) # create an translator instance that has the same lifecycle as the app translator = FluentTranslator() app.installTranslator(translator) w = CalendarPicker() w.show() app.exec() ``` -------------------------------- ### Install ToolTipFilter on a Widget Source: https://github.com/zhiyiyo/qfluentwidgets-docs/blob/main/dev/docs/components/status_info/tool_tip.md Demonstrates how to replace the standard Qt tooltip with a custom QFluentWidgets ToolTip. It involves setting the standard tooltip properties and installing the ToolTipFilter as an event filter on the target widget. ```python button = QPushButton('キラキラ') button.setToolTip('aiko - キラキラ ✨') button.setToolTipDuration(1000) # Install the tooltip filter for the button button.installEventFilter(ToolTipFilter(button, showDelay=300, position=ToolTipPosition.TOP)) ``` -------------------------------- ### Implementing LineEdit Text Input Components Source: https://context7.com/zhiyiyo/qfluentwidgets-docs/llms.txt Shows usage of various text input widgets including standard LineEdit, SearchLineEdit, PasswordLineEdit, and rich text editors. Includes examples of auto-completion, action buttons, and signal handling. ```python from qfluentwidgets import (LineEdit, SearchLineEdit, PasswordLineEdit, TextEdit, PlainTextEdit, TextBrowser, Action, FluentIcon) from PyQt5.QtWidgets import QCompleter, QLineEdit from PyQt5.QtCore import Qt # Basic line edit line_edit = LineEdit() line_edit.setPlaceholderText("Enter your email") line_edit.setText("user@example.com") line_edit.setClearButtonEnabled(True) # Line edit with auto-completion search_terms = ["Star Platinum", "Crazy Diamond", "Gold Experience", "King Crimson"] completer = QCompleter(search_terms, line_edit) completer.setCaseSensitivity(Qt.CaseInsensitive) completer.setMaxVisibleItems(10) line_edit.setCompleter(completer) # Add action buttons to line edit calendar_action = Action(FluentIcon.CALENDAR, "", triggered=lambda: print("Open calendar")) line_edit.addAction(calendar_action, QLineEdit.TrailingPosition) # Search box with search signal search_edit = SearchLineEdit() search_edit.setPlaceholderText("Search...") search_edit.searchSignal.connect(lambda text: print(f"Searching for: {text}")) # Password field with visibility toggle password_edit = PasswordLineEdit() password_edit.setPlaceholderText("Enter password") password_edit.setText("secret123") password_edit.setPasswordVisible(False) # Hide password by default # Rich text editor with Markdown support text_edit = TextEdit() text_edit.setMarkdown("## Heading\n* Item 1\n* Item 2\n* Item 3") print(text_edit.toPlainText()) # Get plain text print(text_edit.toHtml()) # Get HTML # Plain text editor plain_edit = PlainTextEdit() plain_edit.setPlainText("Simple plain text content\nLine 2\nLine 3") print(plain_edit.toPlainText()) # Read-only text browser browser = TextBrowser() browser.setMarkdown("## Documentation\nThis is read-only content.") ``` -------------------------------- ### Define Application Configuration with QConfig Source: https://github.com/zhiyiyo/qfluentwidgets-docs/blob/main/dev/docs/guide/setting.md Demonstrates how to define application configuration items using subclasses of `QConfig`. It shows the use of `ConfigItem` with various validators and serializers, such as `BoolValidator`, `ColorConfigItem`, `OptionsConfigItem`, `RangeConfigItem`, and `EnumSerializer`. This setup allows for automatic loading and saving of configurations from a JSON file. ```python class MvQuality(Enum): """ MV quality enumeration class """ FULL_HD = "Full HD" HD = "HD" SD = "SD" LD = "LD" @staticmethod def values(): return [q.value for q in MvQuality] class Config(QConfig): """ Config of application """ # main window enableAcrylic = ConfigItem("MainWindow", "EnableAcrylic", False, BoolValidator()) playBarColor = ColorConfigItem("MainWindow", "PlayBarColor", "#225F7F") themeMode = OptionsConfigItem("MainWindow", "ThemeMode", "Light", OptionsValidator(["Light", "Dark", "Auto"])) recentPlaysNumber = RangeConfigItem("MainWindow", "RecentPlayNumbers", 300, RangeValidator(10, 300)) # online onlineMvQuality = OptionsConfigItem("Online", "MvQuality", MvQuality.FULL_HD, OptionsValidator(MvQuality), EnumSerializer(MvQuality)) # create config object and initialize it cfg = Config() qconfig.load('config/config.json', cfg) ``` -------------------------------- ### Define QSS Stylesheets for Light and Dark Modes Source: https://github.com/zhiyiyo/qfluentwidgets-docs/blob/main/dev/docs/guide/theme.md Example CSS files showing how to use theme-specific colors and font placeholders provided by QFluentWidgets. ```css /* Light mode qss/light/window.qss */ Window { background-color: rgb(249, 249, 249); } Window>QLabel { color: --ThemeColorPrimary; font: 14px --FontFamilies; } ``` ```css /* Dark mode qss/dark/window.qss */ Window { background-color: rgb(32, 32, 32); } Window>QLabel { color: --ThemeColorPrimary; font: 14px --FontFamilies; } ``` -------------------------------- ### Create RangeSettingCard for Page Size Source: https://github.com/zhiyiyo/qfluentwidgets-docs/blob/main/dev/docs/components/settings/setting_card.md Provides an example of a RangeSettingCard used for managing numerical range configuration items, specifically for setting the page size for online songs. It includes a RangeValidator to define the acceptable range. ```python class Config(QConfig): onlinePageSize = RangeConfigItem("Online", "PageSize", 30, RangeValidator(0, 50)) cfg = Config() qconfig.load("config.json", cfg) card = RangeSettingCard( cfg.onlinePageSize, Fluent.MUSIC, title="Page Size", content="The number of online songs displayed per page" ) ``` -------------------------------- ### Play Local Video with VideoWidget Source: https://github.com/zhiyiyo/qfluentwidgets-docs/blob/main/dev/docs/components/media/video_widget.md Demonstrates how to use the VideoWidget to play a local video file. It requires importing the VideoWidget class and using QUrl to specify the file path. The play() method starts playback. ```python from qfluentwidgets.multimedia import VideoWidget from PyQt6.QtCore import QUrl videoWidget = VideoWidget(self) videoWidget.setVideo(QUrl.fromLocalFile("D:/Video/aiko - シアワセ.mp4")) videoWidget.play() ``` -------------------------------- ### Add and Get Tab Items with TabBar (Python) Source: https://github.com/zhiyiyo/qfluentwidgets-docs/blob/main/dev/docs/components/navigation/tab_bar.md Demonstrates how to initialize a TabBar, add a tab item with a route key, text, icon, and click handler, and retrieve the current tab item. This is useful for basic tab management. ```python tabBar = TabBar() # add tab item tabBar.addTab( routeKey="songInfterface", text="Song", icon="/path/to/icon.png", onClick=lambda: print("Click") ) # get current tab item print(self.tabBar.currentTab()) ``` -------------------------------- ### Create Custom SVG Icons with Theme Support Source: https://github.com/zhiyiyo/qfluentwidgets-docs/blob/main/dev/docs/guide/icon.md Provides a Python example for creating custom SVG icons that adapt to different themes (light/dark) by inheriting from `FluentIconBase` and overriding the `path()` method. The `path()` method dynamically generates the SVG file path based on the current theme, ensuring icons display correctly in both light and dark modes. This is useful for applications requiring unique, theme-aware SVG assets. ```python from enum import Enum from qfluentwidgets import getIconColor, Theme, FluentIconBase, ToolButton class MyFluentIcon(FluentIconBase, Enum): """ Custom icons """ ADD = "Add" CUT = "Cut" COPY = "Copy" def path(self, theme=Theme.AUTO): # getIconColor() return "white" or "black" according to current theme return f':/icons/{self.value}_{getIconColor(theme)}.svg' # create tool button button = ToolButton(MyFluentIcon.ADD) # change icon button.setIcon(MyFluentIcon.CUT) # toggle theme, and the icon will be changed # button.clicked.connect(toggleTheme) # Assuming toggleTheme is imported and connected elsewhere ``` -------------------------------- ### Initialize QFluentWidgets App and Window with Theme Toggle (Python) Source: https://github.com/zhiyiyo/qfluentwidgets-docs/blob/main/dev/docs/components/window/fluent_window.md This Python code snippet demonstrates the initialization of a QFluentWidgets application. It creates a main window, adds a push button that triggers theme switching upon click, and sets up the window's layout and properties. Dependencies include the qfluentwidgets library and PyQt modules. ```python # coding:utf-8 import sys from qfluentwidgets import FluentWidget, toggleTheme, PushButton from qfluentwidgets import FluentIcon as FIF from PyQt5.QtWidgets import QApplication, QVBoxLayout from PyQt5.QtGui import QIcon from PyQt5.QtCore import Qt class Window(FluentWidget): def __init__(self): super().__init__() self.button = PushButton(FIF.CONSTRACT, 'Switch Theme', self) self.vBoxLayout = QVBoxLayout(self) # Disable the mica effect # self.setMicaEffectEnabled(False) # Customize background color # self.setCustomBackgroundColor(Qt.red, Qt.blue) # Toggle theme when the button is clicked self.button.clicked.connect(toggleTheme) # Reserve space for the title bar self.vBoxLayout.setContentsMargins(0, self.titleBar.height(), 0, 0) self.vBoxLayout.addWidget(self.button, 0, Qt.AlignmentFlag.AlignCenter) self.resize(900, 700) self.setWindowIcon(QIcon(':/qfluentwidgets/images/logo.png')) self.setWindowTitle('PyQt-Fluent-Widgets') if __name__ == '__main__': app = QApplication(sys.argv) w = Window() w.show() app.exec() ``` -------------------------------- ### Integrate BreadcrumbBar with QStackedWidget Source: https://github.com/zhiyiyo/qfluentwidgets-docs/blob/main/dev/docs/components/navigation/breadcrumb_bar.md Provides a comprehensive example of using BreadcrumbBar in conjunction with QStackedWidget for navigation. This setup allows users to navigate through different interfaces using the breadcrumb, with dynamic addition of new interfaces. ```python class Demo(QWidget): def __init__(self): super().__init__() self.setStyleSheet('Demo{background:rgb(255,255,255)}') self.breadcrumbBar = BreadcrumbBar(self) self.stackedWidget = QStackedWidget(self) self.lineEdit = LineEdit(self) self.addButton = PrimaryToolButton(FluentIcon.SEND, self) self.vBoxLayout = QVBoxLayout(self) self.lineEditLayout = QHBoxLayout() # Add a new navigation item and sub-interface when the enter key is pressed or the button is clicked self.addButton.clicked.connect(lambda: self.addInterface(self.lineEdit.text())) self.lineEdit.returnPressed.connect(lambda: self.addInterface(self.lineEdit.text())) self.breadcrumbBar.currentItemChanged.connect(self.switchInterface) # Adjust the size of the breadcrumb navigation setFont(self.breadcrumbBar, 26) self.breadcrumbBar.setSpacing(20) self.lineEdit.setPlaceholderText('Enter the name of interface') # Add two navigation items self.addInterface('Home') self.addInterface('Documents') # Initialize layout self.vBoxLayout.setContentsMargins(20, 20, 20, 20) self.vBoxLayout.addWidget(self.breadcrumbBar) self.vBoxLayout.addWidget(self.stackedWidget) self.vBoxLayout.addLayout(self.lineEditLayout) self.lineEditLayout.addWidget(self.lineEdit, 1) self.lineEditLayout.addWidget(self.addButton) self.resize(500, 500) def addInterface(self, text: str): if not text: return w = SubtitleLabel(text) w.setObjectName(uuid1().hex) # Use a randomly generated route key w.setAlignment(Qt.AlignCenter) self.lineEdit.clear() self.stackedWidget.addWidget(w) self.stackedWidget.setCurrentWidget(w) self.breadcrumbBar.addItem(w.objectName(), text) def switchInterface(self, objectName): self.stackedWidget.setCurrentWidget(self.findChild(SubtitleLabel, objectName)) ``` -------------------------------- ### Implement FluentWindow Application Framework Source: https://context7.com/zhiyiyo/qfluentwidgets-docs/llms.txt Demonstrates creating a main application window using FluentWindow, which includes sidebar navigation, sub-interfaces, and custom widget integration. It requires defining unique object names for routing and configuring navigation items. ```python import sys from PyQt5.QtWidgets import QApplication, QFrame, QHBoxLayout from PyQt5.QtCore import Qt from qfluentwidgets import (NavigationItemPosition, FluentWindow, SubtitleLabel, setFont, FluentIcon as FIF) class Widget(QFrame): """Custom sub-interface widget""" def __init__(self, text: str, parent=None): super().__init__(parent=parent) self.label = SubtitleLabel(text, self) self.hBoxLayout = QHBoxLayout(self) setFont(self.label, 24) self.label.setAlignment(Qt.AlignCenter) self.hBoxLayout.addWidget(self.label, 1, Qt.AlignCenter) # Must set a globally unique object name as route key self.setObjectName(text.replace(' ', '-')) class MainWindow(FluentWindow): """Main application window with sidebar navigation""" def __init__(self): super().__init__() # Create sub-interfaces self.homeInterface = Widget('Home Interface', self) self.musicInterface = Widget('Music Interface', self) self.videoInterface = Widget('Video Interface', self) self.settingInterface = Widget('Setting Interface', self) self.albumInterface = Widget('Album Interface', self) self.albumInterface1 = Widget('Album Interface 1', self) self.initNavigation() self.initWindow() def initNavigation(self): # Add sub-interfaces to navigation self.addSubInterface(self.homeInterface, FIF.HOME, 'Home') self.addSubInterface(self.musicInterface, FIF.MUSIC, 'Music library') self.addSubInterface(self.videoInterface, FIF.VIDEO, 'Video library') # Add separator self.navigationInterface.addSeparator() # Add scrollable section self.addSubInterface(self.albumInterface, FIF.ALBUM, 'Albums', NavigationItemPosition.SCROLL) # Add nested sub-interface self.addSubInterface(self.albumInterface1, FIF.ALBUM, 'Album 1', parent=self.albumInterface) # Add bottom navigation item self.addSubInterface(self.settingInterface, FIF.SETTING, 'Settings', NavigationItemPosition.BOTTOM) def initWindow(self): self.resize(900, 700) self.setWindowTitle('PyQt-Fluent-Widgets') if __name__ == '__main__': app = QApplication(sys.argv) w = MainWindow() w.show() app.exec_() ``` -------------------------------- ### Initialize and Configure ComboBox Source: https://github.com/zhiyiyo/qfluentwidgets-docs/blob/main/dev/docs/components/basic_input/combo_box.md Demonstrates how to instantiate a ComboBox, populate it with items, handle selection changes, and manage user data associated with specific options. ```python comboBox = ComboBox() # Add options items = ['shoko', '西宫硝子', '宝多六花', '小鸟游六花'] comboBox.addItems(items) # Signal of current option index change comboBox.currentIndexChanged.connect(lambda index: print(comboBox.currentText())) # Bind data to options comboBox.addItem('leetcode', userData="Sword Pointing to Offer") comboBox.itemData(4) # Placeholder and deselection comboBox.setPlaceholderText("Choose a character") comboBox.setCurrentIndex(-1) ``` -------------------------------- ### Implement IconInfoBadge Source: https://github.com/zhiyiyo/qfluentwidgets-docs/blob/main/dev/docs/components/status_info/info_badge.md Usage examples for IconInfoBadge, which displays a specific icon to represent notification types. ```python IconInfoBadge.info(FluentIcon.ACCEPT_MEDIUM) IconInfoBadge.success(FluentIcon.ACCEPT_MEDIUM) IconInfoBadge.attension(FluentIcon.ACCEPT_MEDIUM) IconInfoBadge.warning(FluentIcon.CANCEL_MEDIUM) IconInfoBadge.error(FluentIcon.CANCEL_MEDIUM) ``` -------------------------------- ### Define and initialize custom configuration Source: https://github.com/zhiyiyo/qfluentwidgets-docs/blob/main/dev/docs/components/settings/config.md Demonstrates how to create a custom configuration class by inheriting from QConfig, defining various ConfigItem types, and initializing the configuration instance from a JSON file. ```python from enum import Enum from qfluentwidgets import * class MvQuality(Enum): """ MV quality enumeration class """ FULL_HD = "Full HD" HD = "HD" SD = "SD" LD = "LD" @staticmethod def values(): return [q.value for q in MvQuality] class MyConfig(QConfig): """ Application's Config """ # main window enableAcrylic = ConfigItem("MainWindow", "EnableAcrylic", False, BoolValidator()) playBarColor = ColorConfigItem("MainWindow", "PlayBarColor", "#225C7F") themeMode = OptionsConfigItem("MainWindow", "ThemeMode", "Light", OptionsValidator(["Light", "Dark", "Auto"]), restart=True) recentPlaysNumber = RangeConfigItem("MainWindow", "RecentPlayNumbers", 300, RangeValidator(10, 300)) # online onlineMvQuality = OptionsConfigItem("Online", "MvQuality", MvQuality.FULL_HD, OptionsValidator(MvQuality), EnumSerializer(MvQuality)) # Create a config instance and initialize it using the configuration file cfg = MyConfig() qconfig.load('config/config.json', cfg) ``` -------------------------------- ### Implement DotInfoBadge Source: https://github.com/zhiyiyo/qfluentwidgets-docs/blob/main/dev/docs/components/status_info/info_badge.md Usage examples for DotInfoBadge, which displays a simple dot to indicate status without numerical values. ```python DotInfoBadge.info() DotInfoBadge.success() DotInfoBadge.attension() DotInfoBadge.warning() DotInfoBadge.error() DotInfoBadge.custom('#005fb8', '#60cdff') ``` -------------------------------- ### Manage Application Theme and Accent Colors Source: https://context7.com/zhiyiyo/qfluentwidgets-docs/llms.txt Demonstrates how to listen for theme and color change signals and how to programmatically set the system accent color on supported platforms. ```python from qfluentwidgets import qconfig, setThemeColor from qframelesswindow.utils import getSystemAccentColor import sys # Listen for theme changes qconfig.themeChanged.connect(lambda theme: print(f"Theme changed to: {theme}")) qconfig.themeColorChanged.connect(lambda color: print(f"Theme color changed to: {color}")) # Get system accent color on Windows/macOS if sys.platform in ["win32", "darwin"]: setThemeColor(getSystemAccentColor(), save=False) ``` -------------------------------- ### Create OptionsSettingCard for Application Theme Source: https://github.com/zhiyiyo/qfluentwidgets-docs/blob/main/dev/docs/components/settings/setting_card.md Shows how to implement an OptionsSettingCard to manage application theme settings. It uses a QConfig object and allows users to select between 'Light', 'Dark', or 'Follow System Settings'. ```python card = OptionsSettingCard( qconfig.themeMode, FluentIcon.BRUSH, "Application Theme", "Adjust the appearance of your application", texts=["Light", "Dark", "Follow System Settings"] ) ``` -------------------------------- ### Initialize and Configure FlipView Source: https://github.com/zhiyiyo/qfluentwidgets-docs/blob/main/dev/docs/components/view/flip_view.md Demonstrates how to instantiate a HorizontalFlipView, add images, and connect to page change signals. ```python flipView = HorizontalFlipView() # Adding images flipView.addImages(["image1.png", "image2.png"]) # Listen to the signal of current page change flipView.currentIndexChanged.connect(lambda index: print("Current page:", index)) ``` -------------------------------- ### Implement DateEdit for date selection Source: https://github.com/zhiyiyo/qfluentwidgets-docs/blob/main/dev/docs/components/text/spin_box.md Provides an example of configuring DateEdit with a specific date range and handling date updates via signals. ```python dateEdit = DateEdit() # Set the range of values dateEdit.setDateRange(QDate(2024, 1, 1), QDate(2024, 11, 11)) # Set the current value dateEdit.setDate(QDate(2024, 2, 2)) # Listen for value change signal dateEdit.dateChanged.connect(lambda date: print("Current date:", date.toString())) # Get the current value print(dateEdit.date()) ``` -------------------------------- ### Define Translation File Metadata Source: https://github.com/zhiyiyo/qfluentwidgets-docs/blob/main/dev/docs/guide/i18n.md Example of the XML structure required for Qt translation files, specifically setting the language attribute within the TS tag. ```xml ``` -------------------------------- ### Basic SplashScreen Implementation in Python Source: https://github.com/zhiyiyo/qfluentwidgets-docs/blob/main/dev/docs/components/window/splash_screen.md This Python code demonstrates the basic usage of the SplashScreen component from qfluentwidgets. It shows how to initialize a splash screen with an icon and parent window, display it during application startup, and then hide it once the main interface is ready. Dependencies include qfluentwidgets and qframelesswindow. ```python # coding:utf-8 from qfluentwidgets import SplashScreen from qframelesswindow import FramelessWindow, StandardTitleBar from PyQt6.QtGui import QIcon, QSize from PyQt6.QtWidgets import QApplication from PyQt6.QtCore import QEventLoop, QTimer import sys class Demo(FramelessWindow): def __init__(self): super().__init__() self.resize(700, 600) self.setWindowTitle('PyQt-Fluent-Widgets') self.setWindowIcon(QIcon(':/qfluentwidgets/images/logo.png')) # 1. Create a splash screen self.splashScreen = SplashScreen(self.windowIcon(), self) self.splashScreen.setIconSize(QSize(102, 102)) # 2. Show the main interface before creating other sub-interfaces self.show() # 3. Create sub-interfaces self.createSubInterface() # 4. Hide the splash screen self.splashScreen.finish() def createSubInterface(self): loop = QEventLoop(self) QTimer.singleShot(3000, loop.quit) loop.exec() if __name__ == '__main__': app = QApplication(sys.argv) w = Demo() w.show() app.exec() ``` -------------------------------- ### Initialize and Populate RoundMenu Source: https://github.com/zhiyiyo/qfluentwidgets-docs/blob/main/dev/docs/components/menu/menu.md Demonstrates how to instantiate a RoundMenu, add individual or batched actions using FluentIcon, and include separators. ```python menu = RoundMenu() # Add actions one by one, Action inherits from QAction and accepts icons of type FluentIconBase menu.addAction(Action(FluentIcon.COPY, 'Copy', triggered=lambda: print("Copy successful"))) menu.addAction(Action(FluentIcon.CUT, 'Cut', triggered=lambda: print("Cut successful"))) # Add actions in batches menu.addActions([ Action(FluentIcon.PASTE, 'Paste'), Action(FluentIcon.CANCEL, 'Undo') ]) # Add a separator menu.addSeparator() menu.addAction(QAction('Select All', shortcut='Ctrl+A')) ``` -------------------------------- ### Create Basic TeachingTip with Python Source: https://github.com/zhiyiyo/qfluentwidgets-docs/blob/main/dev/docs/components/dialog_flyout/teaching_tip.md Demonstrates how to instantiate a TeachingTip with a target widget, icon, title, and content. The tip is configured to automatically close after 2000 milliseconds. ```python class Demo(QWidget): def __init__(self): super().__init__() self.button = PushButton("Click Me", self) self.button.clicked.connect(self.showTeachingTip) self.hBoxLayout = QHBoxLayout(self) self.hBoxLayout.addWidget(self.button, 0, Qt.AlignCenter) self.resize(600, 500) def showTeachingTip(self): TeachingTip.create( target=self.button, icon=InfoBarIcon.SUCCESS, title='Lesson 4', content="Pay your respects, express your respect, and then move on to another new stage of the whirl!", isClosable=True, tailPosition=TeachingTipTailPosition.BOTTOM, duration=2000, parent=self ) ``` -------------------------------- ### Create ElevatedCardWidget in Python Source: https://github.com/zhiyiyo/qfluentwidgets-docs/blob/main/dev/docs/components/layout/card_widget.md Shows how to create a custom ElevatedCardWidget by subclassing ElevatedCardWidget. This example demonstrates arranging an image and a label within the card to display an emoji and its name. ```python class EmojiCard(ElevatedCardWidget): def __init__(self, iconPath: str, name: str, parent=None): super().__init__(parent) self.iconWidget = ImageLabel(iconPath, self) self.label = CaptionLabel(name, self) self.iconWidget.scaledToHeight(68) self.vBoxLayout = QVBoxLayout(self) self.vBoxLayout.setAlignment(Qt.AlignCenter) self.vBoxLayout.addStretch(1) self.vBoxLayout.addWidget(self.iconWidget, 0, Qt.AlignCenter) self.vBoxLayout.addStretch(1) self.vBoxLayout.addWidget(self.label, 0, Qt.AlignHCenter | Qt.AlignBottom) self.setFixedSize(168, 176) ``` -------------------------------- ### Create Custom Navigation Widget Source: https://github.com/zhiyiyo/qfluentwidgets-docs/blob/main/dev/docs/components/navigation/navigation_bar.md Demonstrates how to create a custom navigation item by inheriting from NavigationWidget. This example implements an avatar widget with custom painting logic for background and image rendering. ```python from qfluentwidgets import NavigationWidget class AvatarWidget(NavigationWidget): """ Avatar widget """ def __init__(self, parent=None): super().__init__(isSelectable=False, parent=parent) self.avatar = QImage('resource/shoko.png').scaled( 24, 24, Qt.KeepAspectRatio, Qt.SmoothTransformation) def paintEvent(self, e): painter = QPainter(self) painter.setRenderHints( QPainter.SmoothPixmapTransform | QPainter.Antialiasing) painter.setPen(Qt.NoPen) if self.isPressed: painter.setOpacity(0.7) # draw background if self.isEnter: c = 255 if isDarkTheme() else 0 painter.setBrush(QColor(c, c, c, 10)) painter.drawRoundedRect(self.rect(), 5, 5) # draw avatar painter.setBrush(QBrush(self.avatar)) painter.translate(8, 6) painter.drawEllipse(0, 0, 24, 24) painter.translate(-8, -6) if not self.isCompacted: painter.setPen(Qt.white if isDarkTheme() else Qt.black) font = QFont('Segoe UI') font.setPixelSize(14) painter.setFont(font) painter.drawText(QRect(44, 0, 255, 36), Qt.AlignVCenter, 'zhiyiYo') ``` -------------------------------- ### Create Standard Flyout with Icons and Images Source: https://github.com/zhiyiyo/qfluentwidgets-docs/blob/main/dev/docs/components/dialog_flyout/flyout.md Demonstrates how to instantiate a Flyout using the create method, supporting icons, titles, content, and images. It highlights the use of target elements and animation types for UI consistency. ```python Flyout.create( icon=InfoBarIcon.SUCCESS, title='Lesson 4', content="Pay your respects, express your respect, and then move on to another new stage of the whirl!", target=self.button, parent=self, isClosable=True, aniType=FlyoutAnimationType.PULL_UP ) Flyout.create( image="/path/to/image.png", title='Lesson 4', content="Pay your respects, express your respect, and then move on to another new stage of the whirl!", target=self.button, parent=self, isClosable=False ) ``` -------------------------------- ### Utilize FluentIcon and Custom Icon Sets Source: https://context7.com/zhiyiyo/qfluentwidgets-docs/llms.txt Explains how to use built-in FluentIcons, apply theme-specific colors, and create custom icon sets by inheriting from FluentIconBase. ```python from qfluentwidgets import (FluentIcon, FluentIconBase, ToolButton, getIconColor, Theme, toggleTheme) from PyQt5.QtCore import Qt from PyQt5.QtGui import QColor from enum import Enum button = ToolButton(FluentIcon.SETTING) button.setIcon(FluentIcon.ADD) light_icon = FluentIcon.ADD.icon(Theme.LIGHT) dark_icon = FluentIcon.ADD.icon(Theme.DARK) red_icon = FluentIcon.ADD.icon(color='red') dual_color_icon = FluentIcon.ADD.colored(QColor(255, 0, 0), QColor(0, 0, 255)) class MyFluentIcon(FluentIconBase, Enum): ADD = "Add" def path(self, theme=Theme.AUTO): color = getIconColor(theme) return f':/icons/{self.value}_{color}.svg' custom_btn = ToolButton(MyFluentIcon.ADD) custom_btn.clicked.connect(toggleTheme) ``` -------------------------------- ### Create Custom InfoBar Source: https://github.com/zhiyiyo/qfluentwidgets-docs/blob/main/dev/docs/components/status_info/info_bar.md Creates a custom InfoBar with a specified icon, title, and content. Allows setting orientation, closability, position, duration, and parent. Includes an example of setting a custom background color. ```python w = InfoBar.new( icon=FluentIcon.GITHUB, title='Ripple Dash', content="The song of humanity is the song of courage, and the greatness of humanity is the greatness of courage!", orient=Qt.Horizontal, isClosable=True, position=InfoBarPosition.BOTTOM, duration=2000, parent=window ) w.setCustomBackgroundColor('white', '#202020') ``` -------------------------------- ### Custom Title Bar Implementation Source: https://github.com/zhiyiyo/qfluentwidgets-docs/blob/main/dev/docs/components/window/fluent_window.md Provides a custom title bar implementation for FluentWindow, including tool buttons, a tab bar, and an avatar. This example demonstrates deep customization by replacing the default title bar. ```python from qfluentwidgets import * class CustomTitleBar(MSFluentTitleBar): """ Title bar with icon and title """ def __init__(self, parent): super().__init__(parent) # add buttons self.toolButtonLayout = QHBoxLayout() color = QColor(206, 206, 206) if isDarkTheme() else QColor(96, 96, 96) self.searchButton = TransparentToolButton(FIF.SEARCH_MIRROR.icon(color=color), self) self.forwardButton = TransparentToolButton(FIF.RIGHT_ARROW.icon(color=color), self) self.backButton = TransparentToolButton(FIF.LEFT_ARROW.icon(color=color), self) self.forwardButton.setDisabled(True) self.toolButtonLayout.setContentsMargins(20, 0, 20, 0) self.toolButtonLayout.setSpacing(15) self.toolButtonLayout.addWidget(self.searchButton) self.toolButtonLayout.addWidget(self.backButton) self.toolButtonLayout.addWidget(self.forwardButton) self.hBoxLayout.insertLayout(4, self.toolButtonLayout) # Add tab bar self.tabBar = TabBar(self) self.tabBar.setMovable(True) self.tabBar.setTabMaximumWidth(220) self.tabBar.setTabShadowEnabled(False) self.tabBar.setTabSelectedBackgroundColor(QColor(255, 255, 255, 125), QColor(255, 255, 255, 50)) self.tabBar.tabCloseRequested.connect(self.tabBar.removeTab) self.tabBar.currentChanged.connect(lambda i: print(self.tabBar.tabText(i))) self.hBoxLayout.insertWidget(5, self.tabBar, 1) self.hBoxLayout.setStretch(6, 0) # Add avatar self.avatar = TransparentDropDownToolButton('resource/shoko.png', self) self.avatar.setIconSize(QSize(26, 26)) self.avatar.setFixedHeight(30) self.hBoxLayout.insertWidget(7, self.avatar, 0, Qt.AlignRight) self.hBoxLayout.insertSpacing(8, 20) if sys.platform == "darwin": self.hBoxLayout.insertSpacing(8, 52) def canDrag(self, pos: QPoint): """ Determine whether the mouse click position allows dragging """ if not super().canDrag(pos): return False pos.setX(pos.x() - self.tabBar.x()) return not self.tabBar.tabRegion().contains(pos) class Window(MSFluentWindow): def __init__(self): super().__init__() # Replace the title bar self.setTitleBar(CustomTitleBar(self)) ``` -------------------------------- ### Initialize and Populate CommandBar Source: https://github.com/zhiyiyo/qfluentwidgets-docs/blob/main/dev/docs/components/menu/command_bar.md Demonstrates how to instantiate a CommandBar, add individual or batched actions, and include hidden actions that appear in the overflow menu. ```python commandBar = CommandBar() # Add actions one by one commandBar.addAction(Action(FluentIcon.ADD, 'Add', triggered=lambda: print("Add"))) # Add a separator commandBar.addSeparator() # Add actions in batches commandBar.addActions([ Action(FluentIcon.EDIT, 'Edit', checkable=True, triggered=lambda: print("Edit")), Action(FluentIcon.COPY, 'Copy'), Action(FluentIcon.SHARE, 'Share'), ]) # Add always hidden actions commandBar.addHiddenAction(Action(FluentIcon.SCROLL, 'Sort', triggered=lambda: print('Sort'))) commandBar.addHiddenAction(Action(FluentIcon.SETTING, 'Settings', shortcut='Ctrl+S')) ``` -------------------------------- ### Customizing DatePicker Column Format in Python Source: https://github.com/zhiyiyo/qfluentwidgets-docs/blob/main/dev/docs/components/date_time/date_picker.md Illustrates how to customize the display format of DatePicker columns by inheriting from PickerColumnFormatter. This example shows a custom formatter for the month column, appending an emoji to the displayed month. ```python from qfluentwidgets import DatePicker, PickerColumnFormatter from PyQt6.QtCore import QDate class MonthFormatter(PickerColumnFormatter): """ Month formatter """ def encode(self, value): # Here the range of value is 1-12 return str(value) + "😊" def decode(self, value: str): return int(value[:-1]) # Use the custom month format (first column) datePicker = DatePicker() datePicker.setColumnFormatter(0, MonthFormatter()) ``` -------------------------------- ### Apply Theme-Aware Custom Stylesheets Source: https://context7.com/zhiyiyo/qfluentwidgets-docs/llms.txt Demonstrates creating a custom stylesheet class using StyleSheetBase to ensure UI styles automatically update when the application theme changes. ```python from qfluentwidgets import (StyleSheetBase, Theme, qconfig) from enum import Enum class StyleSheet(StyleSheetBase, Enum): WINDOW = "window" SIDEBAR = "sidebar" def path(self, theme=Theme.AUTO): theme = qconfig.theme if theme == Theme.AUTO else theme return f"qss/{theme.value.lower()}/{self.value}.qss" ``` -------------------------------- ### Create and Position InfoBadge Components Source: https://github.com/zhiyiyo/qfluentwidgets-docs/blob/main/dev/docs/components/status_info/info_badge.md Demonstrates how to instantiate various styles of InfoBadge, attach them to target widgets, and define custom positioning logic using InfoBadgeManager. ```python InfoBadge.info(1) InfoBadge.success(10) InfoBadge.attension(100) InfoBadge.warning(1000) InfoBadge.error(10000) InfoBadge.custom('1w+', '#005fb8', '#60cdff') button = ToolButton(FIF.BASKETBALL, parent) vBoxLayout.addWidget(button, 0, Qt.AlignHCenter) InfoBadge.success(1, parent=parent, target=button, position=InfoBadgePosition.TOP_RIGHT) @InfoBadgeManager.register('Custom') class CustomInfoBadgeManager(InfoBadgeManager): def position(self): pos = self.target.geometry().center() x = pos.x() - self.badge.width() // 2 y = self.target.y() - self.badge.height() // 2 return QPoint(x, y) InfoBadge.success(1, parent=parent, target=button, position="Custom") ``` -------------------------------- ### Implement Pivot Navigation with QFluentWidgets Source: https://github.com/zhiyiyo/qfluentwidgets-docs/blob/main/dev/docs/components/navigation/top_navigation.md Demonstrates how to initialize a Pivot widget, add tab items with unique route keys, and manage active states. It also shows a practical integration with QStackedWidget to handle page transitions based on user selection. ```python pivot = Pivot() # Add tab items pivot.addItem(routeKey="songInterface", text="Song", onClick=lambda: print("Song")) pivot.addItem(routeKey="albumInterface", text="Album", onClick=lambda: print("Album")) pivot.addItem(routeKey="artistInterface", text="Artist", onClick=lambda: print("Artist")) # Set the current tab item pivot.setCurrentItem("albumInterface") # Get the current tab item print(pivot.currentItem()) ``` ```python class Demo(QWidget): def __init__(self): super().__init__() self.pivot = Pivot(self) self.stackedWidget = QStackedWidget(self) self.vBoxLayout = QVBoxLayout(self) self.songInterface = QLabel('Song Interface', self) self.albumInterface = QLabel('Album Interface', self) self.artistInterface = QLabel('Artist Interface', self) # Add tabs self.addSubInterface(self.songInterface, 'songInterface', 'Song') self.addSubInterface(self.albumInterface, 'albumInterface', 'Album') self.addSubInterface(self.artistInterface, 'artistInterface', 'Artist') # Connect signal and initialize the current tab self.stackedWidget.currentChanged.connect(self.onCurrentIndexChanged) self.stackedWidget.setCurrentWidget(self.songInterface) self.pivot.setCurrentItem(self.songInterface.objectName()) self.vBoxLayout.setContentsMargins(30, 0, 30, 30) self.vBoxLayout.addWidget(self.pivot, 0, Qt.AlignHCenter) self.vBoxLayout.addWidget(self.stackedWidget) self.resize(400, 400) def addSubInterface(self, widget: QLabel, objectName: str, text: str): widget.setObjectName(objectName) widget.setAlignment(Qt.AlignCenter) self.stackedWidget.addWidget(widget) # Use the globally unique objectName as the route key self.pivot.addItem( routeKey=objectName, text=text, onClick=lambda: self.stackedWidget.setCurrentWidget(widget) ) def onCurrentIndexChanged(self, index): widget = self.stackedWidget.widget(index) self.pivot.setCurrentItem(widget.objectName()) ``` -------------------------------- ### Create FolderListSettingCard for Local Music Folders Source: https://github.com/zhiyiyo/qfluentwidgets-docs/blob/main/dev/docs/components/settings/setting_card.md Illustrates the creation of a FolderListSettingCard for managing local music library folders. It utilizes a QConfig object with a FolderListValidator and allows selection of a directory. ```python class Config(QConfig): ConfigItem("Folders", "LocalMusic", [], FolderListValidator()) cfg = Config() qconfig.load("config.json", cfg) card = FolderListSettingCard( cfg.musicFolders, "Local Music Library", directory=QStandardPaths.writableLocation(QStandardPaths.MusicLocation), parent=self.musicInThisPCGroup ) ``` -------------------------------- ### Configure Multi-language Support in VuePress Source: https://github.com/zhiyiyo/qfluentwidgets-docs/blob/main/README.md Configuration snippets for adding new languages to the VuePress theme and site configuration files. These changes involve updating the locale objects in both the theme configuration and the main user configuration. ```javascript import * as zhConfig from './zh' import * as enConfig from './en' import * as jpConfig from './jp' export const themeConfig = { locales: { '/': { selectLanguageText: 'Languages', selectLanguageName: 'English', ...enConfig, }, '/zh/': { selectLanguageText: '选择语言', selectLanguageName: '简体中文', ...zhConfig, }, '/jp/': { selectLanguageText: '言語', selectLanguageName: '日本語', ...jpConfig, }, } } ``` ```typescript export default defineUserConfig({ locales: { '/': { lang: 'English', title: 'QFluentWidgets', description: "QFluentWidgets - Fluent Design Components Library", }, '/zh/': { lang: '简体中文', title: "QFluentWidgets", description: "QFluentWidgets - Fluent Design 风格组件库", }, '/jp/': { lang: '日本語', title: 'QFluentWidgets', description: "QFluentWidgets - Fluent Designスタイルコンポーネントライブラリ", }, } }); ``` -------------------------------- ### Create Modal Dialogs and Custom Message Boxes Source: https://context7.com/zhiyiyo/qfluentwidgets-docs/llms.txt Explains how to use standard MessageBox and Dialog components, and how to extend MessageBoxBase to build custom dialogs with form validation. ```python from qfluentwidgets import MessageBox, MessageBoxBase, SubtitleLabel, LineEdit, CaptionLabel from PyQt5.QtCore import QUrl from PyQt5.QtGui import QColor # Simple message box def show_confirmation(parent_window): w = MessageBox("Confirm", "Are you sure?", parent_window) if w.exec(): print("Confirmed") # Custom dialog with validation class URLInputDialog(MessageBoxBase): def __init__(self, parent=None): super().__init__(parent) self.urlLineEdit = LineEdit() self.viewLayout.addWidget(self.urlLineEdit) def validate(self): return QUrl(self.urlLineEdit.text()).isValid() ``` -------------------------------- ### CalendarPicker: Select and Handle Dates in Python Source: https://github.com/zhiyiyo/qfluentwidgets-docs/blob/main/dev/docs/components/date_time/calandar_picker.md Demonstrates how to use the CalendarPicker widget to set, get, and react to date changes. It requires the QDate and Qt modules from PyQt. The widget emits a dateChanged signal when the selected date is modified. ```python from qfluentwidgets import CalendarPicker from PyQt6.QtCore import QDate, Qt calendarPicker = CalendarPicker() # Set the current date calendarPicker.setDate(QDate(2024, 2, 26)) # Get the current date print(calendarPicker.date) # Date changes calendarPicker.dateChanged.connect(lambda date: print(date.toString())) # Set date format: calendarPicker.setDateFormat(Qt.TextDate) calendarPicker.setDateFormat('yyyy-M-d') ```