mirror of
https://github.com/sanjeed5/awesome-cursor-rules-mdc.git
synced 2026-11-30 23:04:59 +08:00
Regenerate all MDC rules with fresh Exa data and December 2025 best practices
- Refreshed all 241 library rules with current best practices - Updated Exa search results for all libraries with 2025 content - Fixed --regenerate-all flag logic to properly process all libraries - Removed duplicate astro entry in rules.json (merged tags) - Added missing docker.mdc and vim.mdc files - All rules now include modern patterns and anti-patterns - Updated with framework-specific recommendations for 2025 Technical improvements: - Fixed retry_failed_only logic in generate_mdc_files.py - Improved progress tracking for regeneration scenarios - Ensured proper handling of --refresh-exa flag
This commit is contained in:
+285
-99
@@ -1,120 +1,306 @@
|
||||
---
|
||||
description: This rule file provides comprehensive guidelines for PyQt development, covering code organization, common patterns, performance, security, testing, and tooling. It aims to help developers create maintainable, efficient, and secure PyQt applications.
|
||||
globs: *.py
|
||||
description: Enforce modern, maintainable, and performant PyQt application development standards by leveraging Qt Designer, Model-View architecture, and responsive threading.
|
||||
globs: **/*.py
|
||||
---
|
||||
- **Follow Consistent Importing:**
|
||||
- Avoid wildcard imports like `from PyQt5.QtGui import *`. They clutter the namespace and can lead to naming conflicts.
|
||||
- Instead, import only the necessary modules or classes, e.g., `from PyQt5 import QtGui` and access members with the module prefix: `QtGui.QPushButton`.
|
||||
- *Rationale:* Improves code readability and avoids potential namespace collisions.
|
||||
# PyQt Best Practices
|
||||
|
||||
- **Adhere to Naming Conventions:**
|
||||
- Follow Qt's camelCase style for method names (e.g., `loadItems()`, `refreshResults()`). This maintains consistency with the Qt API and reduces confusion.
|
||||
- For signals and slots, consistently use camelCase.
|
||||
- *Rationale:* Ensures consistency with Qt's API and reduces cognitive load for developers.
|
||||
This guide outlines essential practices for building robust, scalable, and maintainable PyQt applications. Adhere to these rules for consistent, high-quality code.
|
||||
|
||||
- **Separate GUI and Business Logic (MVC or similar):**
|
||||
- Keep GUI code separate from business logic using patterns like Model-View-Controller (MVC), Model-View-Presenter (MVP), or Model-View-ViewModel (MVVM).
|
||||
- *Model:* Represents the data and business logic.
|
||||
- *View:* Displays the data to the user.
|
||||
- *Controller/Presenter/ViewModel:* Handles user input and updates the Model and View.
|
||||
- *Rationale:* Enhances maintainability, testability, and scalability by decoupling concerns.
|
||||
## 1. UI Design: Qt Designer & Dynamic Loading
|
||||
|
||||
- **Leverage Qt Designer (or Alternatives):**
|
||||
- Use Qt Designer (or alternative tools like QML) for layout management and rapid prototyping.
|
||||
- Load the generated `.ui` files into your Python code using `PyQt6.uic.loadUi`.
|
||||
- *Rationale:* Speeds up GUI development and simplifies layout design.
|
||||
Always design your UI visually with **Qt Designer** (or Qt Design Studio). Keep the generated `.ui` files pristine. Load them dynamically at runtime or integrate the `pyuic`-generated code via inheritance without modification. This separates design from logic and simplifies UI updates.
|
||||
|
||||
- **Employ Signals and Slots:**
|
||||
- Use Qt's signals and slots mechanism for communication between objects.
|
||||
- Connect signals to slots using `QObject.connect()` or the newer, more Pythonic syntax in PyQt6.
|
||||
- *Rationale:* Provides a type-safe and flexible way to handle events and user interactions.
|
||||
❌ **BAD: Hand-editing `pyuic`-generated files**
|
||||
```python
|
||||
# ui_mainwindow.py (DO NOT EDIT THIS FILE DIRECTLY)
|
||||
# This file was generated by pyuic6...
|
||||
class Ui_MainWindow(object):
|
||||
def setupUi(self, MainWindow):
|
||||
# ... generated code ...
|
||||
self.my_custom_button.clicked.connect(self.my_logic_function) # Added here
|
||||
```
|
||||
|
||||
- **Protect UI Members:**
|
||||
- Treat UI components defined in Qt Designer as protected or private members.
|
||||
- Provide access to child widgets of your class through methods instead of direct access.
|
||||
- *Rationale:* Facilitates future modifications to the UI without breaking external code.
|
||||
✅ **GOOD: Dynamic loading with `QUiLoader` (PyQt6)**
|
||||
```python
|
||||
from PyQt6.QtWidgets import QApplication, QWidget
|
||||
from PyQt6.uic import loadUi
|
||||
|
||||
- **Naming Conventions for Designer Components:**
|
||||
- Adopt a consistent naming convention for UI components created in Qt Designer.
|
||||
- Use prefixes like `ui_` to indicate that a component was created in Designer (e.g., `ui_project_combo`, `uiProjectCombo`). Append the component type.
|
||||
- *Rationale:* Improves code readability and makes it easier to identify the origin and purpose of UI components.
|
||||
class MyMainWindow(QWidget):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
loadUi("mainwindow.ui", self) # Load UI dynamically
|
||||
self.my_button.clicked.connect(self._on_button_clicked)
|
||||
|
||||
- **Getter and Setter Guidelines:**
|
||||
- Use getter and setter methods to access and modify internal data instead of directly exposing public members. Use camelCase for both the getter and setter methods.
|
||||
- Create protected members using a single leading underscore (e.g., `_value`).
|
||||
- *Rationale:* Provides encapsulation, allows for future changes to the internal implementation, and maintains consistency with Qt's style.
|
||||
def _on_button_clicked(self):
|
||||
print("Button clicked!")
|
||||
|
||||
- **Never Expose Public Members in Qt Classes:**
|
||||
- In Python, there isn't a strict public/protected/private syntax, but use underscores to flag different types of data.
|
||||
- Python uses underscores to flag different types of data.
|
||||
- `No underscores`: public variable/member
|
||||
- `1 opening underscore`: protected variable/member
|
||||
- `1 trailing underscore`: used when defining a variable that would otherwise clash with a Python internal
|
||||
- `2 opening underscores`: private variable/member (does some funkiness under the hood so it becomes pretty hard to access from outside your class or module)
|
||||
- `2 opening underscores and 2 trailing underscores`: built-in, usually used by internal python variables and methods
|
||||
- When developing new Qt objects, widgets, or classes you should create protected members, and allow access to them via getter and setter methods.
|
||||
if __name__ == "__main__":
|
||||
app = QApplication([])
|
||||
window = MyMainWindow()
|
||||
window.show()
|
||||
app.exec()
|
||||
```
|
||||
|
||||
- **Code Organization and Structure:**
|
||||
- *Directory Structure:* Organize your project into logical directories (e.g., `ui`, `models`, `controllers`, `widgets`).
|
||||
- *File Naming:* Use descriptive file names (e.g., `mainwindow.py`, `user_model.py`).
|
||||
- *Module Organization:* Break your code into smaller, reusable modules.
|
||||
- *Component Architecture:* Design your application using a component-based architecture for better modularity.
|
||||
✅ **GOOD: Single inheritance with `pyuic`-generated code**
|
||||
```python
|
||||
# ui_mainwindow.py (Generated by `pyuic6 -o ui_mainwindow.py mainwindow.ui`)
|
||||
# DO NOT EDIT THIS FILE.
|
||||
from PyQt6 import QtWidgets # ... other imports ...
|
||||
class Ui_MainWindow(object):
|
||||
def setupUi(self, MainWindow):
|
||||
# ... generated UI setup code ...
|
||||
pass # No signal connections here
|
||||
|
||||
- **Common Patterns and Anti-Patterns:**
|
||||
- *Design Patterns:* Apply design patterns like Observer, Singleton, Factory, and Strategy where appropriate.
|
||||
- *Anti-Patterns:* Avoid God classes, tight coupling, and code duplication.
|
||||
- *State Management:* Use signals and slots or dedicated state management libraries for managing application state.
|
||||
- *Error Handling:* Implement robust error handling using try-except blocks and logging.
|
||||
# main.py (Your application logic)
|
||||
from PyQt6.QtWidgets import QApplication, QMainWindow
|
||||
from ui_mainwindow import Ui_MainWindow # Import generated UI
|
||||
|
||||
- **Performance Considerations:**
|
||||
- *Optimization:* Optimize your code by minimizing expensive operations, using caching, and avoiding unnecessary GUI updates.
|
||||
- *Memory Management:* Be mindful of memory usage, especially when dealing with large images or data sets. Use `del` to remove unwanted objects from memory.
|
||||
- *Rendering Optimization:* Optimize rendering by using double buffering, avoiding unnecessary repaints, and using optimized drawing methods.
|
||||
- Deleting objects that are no longer in use.
|
||||
- Limit the number of widgets.
|
||||
class MyMainWindow(QMainWindow):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.ui = Ui_MainWindow()
|
||||
self.ui.setupUi(self) # Set up the UI on this window
|
||||
self.ui.my_button.clicked.connect(self._on_button_clicked)
|
||||
|
||||
- **Security Best Practices:**
|
||||
- *Vulnerabilities:* Be aware of common vulnerabilities like code injection, cross-site scripting (XSS), and SQL injection if using databases.
|
||||
- *Input Validation:* Validate all user inputs to prevent malicious data from entering your application.
|
||||
- *Authentication:* Implement proper authentication and authorization mechanisms to protect sensitive data.
|
||||
- *Data Protection:* Encrypt sensitive data and use secure communication protocols.
|
||||
- When fetching external data be mindful about malicious data.
|
||||
def _on_button_clicked(self):
|
||||
print("Button clicked from inherited UI!")
|
||||
|
||||
- **Testing Approaches:**
|
||||
- *Unit Tests:* Write unit tests for individual components and functions.
|
||||
- *Integration Tests:* Test the interaction between different components.
|
||||
- *End-to-End Tests:* Test the entire application flow.
|
||||
- *Test Organization:* Organize your tests into logical directories and use meaningful names.
|
||||
- *Mocking:* Use mocking and stubbing to isolate components during testing.
|
||||
- Using `pytest` to generate tests.
|
||||
if __name__ == "__main__":
|
||||
app = QApplication([])
|
||||
window = MyMainWindow()
|
||||
window.show()
|
||||
app.exec()
|
||||
```
|
||||
|
||||
- **Common Pitfalls and Gotchas:**
|
||||
- *Mistakes:* Avoid circular dependencies, memory leaks, and neglecting event handling.
|
||||
- *Edge Cases:* Be aware of edge cases like unexpected user inputs, network errors, and file system issues.
|
||||
- *Version Issues:* Pay attention to version-specific issues and compatibility concerns when upgrading PyQt or other dependencies.
|
||||
- Ensure the GUI thread is kept responsive.
|
||||
## 2. Component Architecture: Model-View Separation
|
||||
|
||||
- **Tooling and Environment:**
|
||||
- *Development Tools:* Use IDEs like VS Code with Python extensions, PyCharm, or Qt Creator.
|
||||
- *Build Configuration:* Use build tools like CMake or setuptools for managing your project build process.
|
||||
- *Linting:* Lint your code using tools like Pylint or Flake8.
|
||||
- *Formatting:* Format your code using tools like Black or autopep8.
|
||||
- *Deployment:* Use tools like PyInstaller or cx_Freeze for creating standalone executables.
|
||||
- *CI/CD:* Integrate your project with CI/CD pipelines for automated testing and deployment.
|
||||
For any data-driven UI (lists, tables, trees), adopt the **Model-View architecture**. This decouples data management from UI presentation, leading to cleaner, more scalable code.
|
||||
|
||||
- **Specific Recommendations:**
|
||||
- Always make sure that long running process happen in the background.
|
||||
- Utilize `QThread` to move computationally heavy process off the main thread.
|
||||
❌ **BAD: Storing data directly in widgets**
|
||||
```python
|
||||
from PyQt6.QtWidgets import QListWidget, QListWidgetItem
|
||||
# ...
|
||||
self.my_list_widget = QListWidget()
|
||||
self.my_list_widget.addItem("Item 1")
|
||||
self.my_list_widget.addItem("Item 2")
|
||||
# To update: self.my_list_widget.item(0).setText("New Item 1") # Tedious
|
||||
```
|
||||
|
||||
- **Code Splitting:**
|
||||
- Break large classes and functions into smaller, more manageable units.
|
||||
- Extract reusable code into separate modules or libraries.
|
||||
✅ **GOOD: Custom `QAbstractListModel` for data**
|
||||
```python
|
||||
from PyQt6.QtCore import QAbstractListModel, QModelIndex, Qt
|
||||
from PyQt6.QtWidgets import QListView, QApplication
|
||||
|
||||
- **State Management Best Practices:**
|
||||
- Use signals and slots effectively to propagate state changes throughout the application.
|
||||
- Consider using a dedicated state management library or pattern if your application has complex state requirements.
|
||||
class MyListModel(QAbstractListModel):
|
||||
def __init__(self, data=None):
|
||||
super().__init__()
|
||||
self._data = data or []
|
||||
|
||||
- **Additional Considerations:**
|
||||
- If you need to handle asynchronous operations, leverage `QFuture` and `QThreadPool` for efficient execution.
|
||||
- Use `QSettings` to store application settings and preferences.
|
||||
- Prioritize accessibility by ensuring your application is usable by people with disabilities (e.g., provide keyboard navigation, use appropriate color contrast).
|
||||
def data(self, index: QModelIndex, role: int):
|
||||
if role == Qt.ItemDataRole.DisplayRole:
|
||||
return self._data[index.row()]
|
||||
return None
|
||||
|
||||
def rowCount(self, parent: QModelIndex):
|
||||
return len(self._data)
|
||||
|
||||
def add_item(self, item: str):
|
||||
self.beginInsertRows(QModelIndex(), len(self._data), len(self._data))
|
||||
self._data.append(item)
|
||||
self.endInsertRows()
|
||||
|
||||
# ... in your QMainWindow or QWidget
|
||||
# self.my_list_view = QListView()
|
||||
# self.model = MyListModel(["Initial Item 1", "Initial Item 2"])
|
||||
# self.my_list_view.setModel(self.model)
|
||||
# self.model.add_item("New Item from Logic") # Model updates view automatically
|
||||
```
|
||||
|
||||
## 3. Asynchronous Operations: Keep UI Responsive
|
||||
|
||||
Never block the UI thread with long-running tasks. Use `QThreadPool` with `QRunnable` or `QThread` for background processing. Emit signals from worker threads to update the UI on the main thread.
|
||||
|
||||
❌ **BAD: Blocking UI thread**
|
||||
```python
|
||||
import time
|
||||
from PyQt6.QtWidgets import QPushButton, QLabel
|
||||
# ...
|
||||
def on_heavy_button_clicked(self):
|
||||
self.status_label.setText("Processing...")
|
||||
time.sleep(5) # UI freezes for 5 seconds
|
||||
self.status_label.setText("Done!")
|
||||
```
|
||||
|
||||
✅ **GOOD: Offload to `QThreadPool`**
|
||||
```python
|
||||
from PyQt6.QtCore import QRunnable, QThreadPool, pyqtSignal, QObject
|
||||
from PyQt6.QtWidgets import QPushButton, QLabel, QApplication, QWidget
|
||||
import time
|
||||
|
||||
class WorkerSignals(QObject):
|
||||
finished = pyqtSignal()
|
||||
result = pyqtSignal(str)
|
||||
|
||||
class Worker(QRunnable):
|
||||
def __init__(self, task_id):
|
||||
super().__init__()
|
||||
self.signals = WorkerSignals()
|
||||
self.task_id = task_id
|
||||
|
||||
def run(self):
|
||||
time.sleep(2) # Simulate heavy work
|
||||
self.signals.result.emit(f"Task {self.task_id} completed.")
|
||||
self.signals.finished.emit()
|
||||
|
||||
class MyWindow(QWidget):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.threadpool = QThreadPool()
|
||||
self.button = QPushButton("Start Heavy Task", self)
|
||||
self.label = QLabel("Ready", self)
|
||||
self.button.clicked.connect(self._start_task)
|
||||
# ... layout setup ...
|
||||
|
||||
def _start_task(self):
|
||||
self.label.setText("Processing...")
|
||||
worker = Worker(time.time()) # Unique ID for task
|
||||
worker.signals.result.connect(self.label.setText)
|
||||
worker.signals.finished.connect(lambda: print("Worker finished"))
|
||||
self.threadpool.start(worker)
|
||||
|
||||
if __name__ == "__main__":
|
||||
app = QApplication([])
|
||||
window = MyWindow()
|
||||
window.show()
|
||||
app.exec()
|
||||
```
|
||||
|
||||
## 4. Communication: Signals & Slots
|
||||
|
||||
Leverage Qt's powerful signals and slots mechanism for decoupled communication between UI components and business logic.
|
||||
|
||||
❌ **BAD: Direct method calls for UI events**
|
||||
```python
|
||||
# In MainWindow
|
||||
self.login_button.clicked.connect(self.login_manager.authenticate) # login_manager is tightly coupled
|
||||
```
|
||||
|
||||
✅ **GOOD: Decoupled signals and slots**
|
||||
```python
|
||||
from PyQt6.QtCore import pyqtSignal, QObject
|
||||
# ...
|
||||
class LoginManager(QObject):
|
||||
login_successful = pyqtSignal(str)
|
||||
login_failed = pyqtSignal(str)
|
||||
|
||||
def authenticate(self, username, password):
|
||||
if username == "user" and password == "pass":
|
||||
self.login_successful.emit("Welcome!")
|
||||
else:
|
||||
self.login_failed.emit("Invalid credentials.")
|
||||
|
||||
# In MainWindow
|
||||
# self.login_manager = LoginManager()
|
||||
# self.login_manager.login_successful.connect(self.show_dashboard)
|
||||
# self.login_manager.login_failed.connect(self.display_error)
|
||||
# self.login_button.clicked.connect(lambda: self.login_manager.authenticate(self.user_input.text(), self.pass_input.text()))
|
||||
```
|
||||
|
||||
## 5. Code Organization & Naming
|
||||
|
||||
Follow Pythonic naming conventions (`CamelCase` for Qt classes, `snake_case` for methods/variables). Organize code into logical modules (e.g., `ui/`, `models/`, `workers/`). Use Qt resource files (`.qrc`) for icons, images, and stylesheets.
|
||||
|
||||
❌ **BAD: Inconsistent naming, monolithic files**
|
||||
```python
|
||||
# myapp.py
|
||||
class my_main_window(QtWidgets.QMainWindow): # Incorrect class name
|
||||
def __init__(self):
|
||||
self.MyButton = QtWidgets.QPushButton() # Incorrect variable name
|
||||
# ... all logic here ...
|
||||
```
|
||||
|
||||
✅ **GOOD: Consistent naming, modular structure**
|
||||
```python
|
||||
# main.py
|
||||
from PyQt6.QtWidgets import QApplication
|
||||
from my_app.ui.main_window import MainWindow # Separate UI module
|
||||
|
||||
if __name__ == "__main__":
|
||||
app = QApplication([])
|
||||
main_window = MainWindow()
|
||||
main_window.show()
|
||||
app.exec()
|
||||
|
||||
# my_app/ui/main_window.py
|
||||
from PyQt6.QtWidgets import QMainWindow
|
||||
# ...
|
||||
class MainWindow(QMainWindow): # CamelCase for Qt classes
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self._setup_ui() # Private helper method
|
||||
self._connect_signals()
|
||||
|
||||
def _on_button_clicked(self): # snake_case for methods
|
||||
pass
|
||||
|
||||
# my_app/resources.qrc (compiled to my_app/resources_rc.py)
|
||||
# <RCC>
|
||||
# <qresource prefix="/icons">
|
||||
# <file>icon.png</file>
|
||||
# </qresource>
|
||||
# </RCC>
|
||||
# Use: self.setWindowIcon(QIcon(":/icons/icon.png"))
|
||||
```
|
||||
|
||||
## 6. Styling & Theming
|
||||
|
||||
Use Qt's stylesheet system (CSS-like `.qss` files) for styling. This allows for easy theming (e.g., dark mode) without modifying Python code.
|
||||
|
||||
❌ **BAD: Hardcoding styles in Python**
|
||||
```python
|
||||
self.my_button.setStyleSheet("background-color: red; color: white;") # Hardcoded
|
||||
```
|
||||
|
||||
✅ **GOOD: External stylesheets**
|
||||
```python
|
||||
# styles.qss
|
||||
QPushButton {
|
||||
background-color: #2196F3; /* Blue */
|
||||
color: white;
|
||||
border: none;
|
||||
padding: 8px 16px;
|
||||
border-radius: 4px;
|
||||
}
|
||||
QPushButton:hover {
|
||||
background-color: #1976D2; /* Darker Blue */
|
||||
}
|
||||
|
||||
# In main.py or MainWindow __init__
|
||||
with open("styles.qss", "r") as f:
|
||||
_stylesheet = f.read()
|
||||
app.setStyleSheet(_stylesheet) # Apply globally
|
||||
# Or self.my_widget.setStyleSheet(_stylesheet) # Apply locally
|
||||
```
|
||||
|
||||
## 7. Type Hints
|
||||
|
||||
Always use Python type hints for improved readability, maintainability, and static analysis.
|
||||
|
||||
❌ **BAD: Untyped code**
|
||||
```python
|
||||
def process_data(data):
|
||||
# ...
|
||||
```
|
||||
|
||||
✅ **GOOD: Type-hinted code**
|
||||
```python
|
||||
from typing import List, Tuple
|
||||
from PyQt6.QtCore import QModelIndex
|
||||
|
||||
def process_data(data: List[Tuple[bool, str]]) -> List[str]:
|
||||
# ...
|
||||
return [item[1] for item in data]
|
||||
|
||||
def data(self, index: QModelIndex, role: int) -> str | None:
|
||||
# ...
|
||||
```
|
||||
Reference in New Issue
Block a user