Я создаю приложение PySide6 и пытаюсь создать два окна с закругленными углами. Одно окно работает нормально, но другое, похоже, не учитывает стиль border-radius, хотя код похож.
Вот два фрагмента кода, которые я использую:
программа пытается скруглить углы:
mport sys
from PySide6.QtCore import Qt, QSize, QRect
from PySide6.QtGui import QPainter, QPainterPath, QColor
from PySide6.QtWidgets import QApplication, QMainWindow, QWidget, QVBoxLayout, QPushButton
class NordMediaPlayer(QMainWindow):
def __init__(self):
super().__init__()
# Make the window frameless
self.setWindowFlags(Qt.FramelessWindowHint)
self.setAttribute(Qt.WA_TranslucentBackground) # Allow transparency for rounded corners
# Window size setup to 250x250
self.setFixedSize(250, 250)
# Example content layout
self.main_widget = QWidget()
self.layout = QVBoxLayout(self.main_widget)
self.button = QPushButton("Play Music", self.main_widget)
self.layout.addWidget(self.button)
self.setCentralWidget(self.main_widget)
def paintEvent(self, event):
"""Override paintEvent to directly paint the rounded corners with anti-aliasing."""
painter = QPainter(self)
# Enable anti-aliasing for smoother edges
painter.setRenderHint(QPainter.Antialiasing)
# Create a path for the rounded rectangle
path = QPainterPath()
rect = QRect(0, 0, self.width(), self.height())
radius = min(self.width(), self.height()) * 0.1 # Adjust the corner radius as needed.
path.addRoundedRect(rect, radius, radius)
# Set the background color (can be customized)
painter.setBrush(QColor(45, 45, 48)) # Example background color (dark gray).
painter.setPen(Qt.transparent) # No border for the rounded rectangle
# Fill the path with the background color (smooth rounded corners)
painter.drawPath(path) # Draw the rounded shape directly
# End painting process
painter.end()
def mousePressEvent(self, event):
"""Handle mouse press event to start dragging the window."""
self.drag_position = event.globalPosition().toPoint()
def mouseMoveEvent(self, event):
"""Handle mouse move event to drag the window."""
if event.buttons() == Qt.LeftButton:
delta = event.globalPosition().toPoint() - self.drag_position
self.move(self.pos() + delta)
self.drag_position = event.globalPosition().toPoint()
def mouseReleaseEvent(self, event):
"""Handle mouse release event to stop dragging the window."""
self.drag_position = None
if __name__ == "__main__":
app = QApplication(sys.argv)
window = NordMediaPlayer()
window.show()
sys.exit(app.exec())
В коде 2 окно отображает закругленные углы, но в коде 1, несмотря на использование того же радиуса границы и аналогичного стиля, углы не закруглены. Я также добавил window2.setWindowFlags(Qt.FramelessWindowHint), чтобы сделать окно безрамочным, но кажется, что закругленные углы больше не применяются должным образом.
Может ли кто-нибудь объяснить, почему код 1 не работает? показать закругленные углы? Нужно ли что-то настроить при использовании Qt.FramelessWindowHint?
Спасибо за любую помощь!
пытаюсь скруглить углы в безрамочном окне
п>
Я создаю приложение PySide6 и пытаюсь создать два окна с закругленными углами. Одно окно работает нормально, но другое, похоже, не учитывает стиль border-radius, хотя код похож. Вот два фрагмента кода, которые я использую: программа пытается скруглить углы: [code]import sys from PySide6.QtCore import Qt, QSize, QMargins from PySide6.QtGui import QIcon, QPixmap, QMouseEvent, QStandardItemModel # Import QStandardItemModel from QtGui from PySide6.QtWidgets import QApplication, QMainWindow, QPushButton, QHBoxLayout, QVBoxLayout, QLabel, QWidget, QLineEdit, QSizeGrip, QFileSystemModel, QTreeView, QListView
class NordMediaPlayer(QMainWindow): def __init__(self): super().__init__()
# Initialize dragging and resizing state self._dragging = False self._drag_position = None self._resizing = False self._resize_direction = None
self.setWindowTitle("shax0") self.setWindowFlags(Qt.FramelessWindowHint) # Remove original title bar self.resize(250, 250) # Set default window size self.setStyleSheet("background-color: #ECEFF4; color: #2E3440;") # Light Nord theme
# Create the main container for the title bar, cover art, and control bar self.mainContainer = QWidget(self) self.mainLayout = QVBoxLayout(self.mainContainer) self.mainLayout.setContentsMargins(0, 0, 0, 0) self.mainLayout.setSpacing(0)
# Title bar self.titleBar = self.createTitleBar() self.mainLayout.addWidget(self.titleBar)
# Cover art area self.coverArt = self.createCoverArt() self.mainLayout.addWidget(self.coverArt)
# Control bar self.controlBar = self.createControlBar() self.mainLayout.addWidget(self.controlBar)
# Command bar (terminal) self.commandBar = QLineEdit(self) self.commandBar.setStyleSheet("background-color: #2E3440; color: #ECEFF4; font-family: Mononoki; font-size: 14px; border: none;") self.commandBar.setPlaceholderText("Enter command...") self.commandBar.setFixedHeight(30) # Set fixed height for command bar self.commandBar.setVisible(False) # Initially hidden self.mainLayout.addWidget(self.commandBar)
# File explorer widget self.fileExplorerWidget = QWidget(self) self.fileExplorerWidget.setVisible(False) self.fileExplorerWidget.setFixedHeight(150) # Limit the height of the file explorer self.mainLayout.addWidget(self.fileExplorerWidget)
# QFileSystemModel and QTreeView for file explorer self.fileSystemModel = QFileSystemModel() self.fileSystemModel.setRootPath('')
def createCoverArt(self): """Create a placeholder for the cover art.""" coverArtWidget = QLabel() coverArtWidget.setAlignment(Qt.AlignCenter) coverArtWidget.setStyleSheet(""" background-color: #ECEFF4; border: none; font-family: Mononoki; color: #2E3440; font-size: 12px; """) coverArtWidget.setText("shax0") return coverArtWidget
def createControlBar(self): """Create the control bar.""" controlBarWidget = QWidget(self) controlBarLayout = QHBoxLayout(controlBarWidget) controlBarLayout.setContentsMargins(0, 0, 0, 0) # No margins for control bar controlBarLayout.setSpacing(0)
# Set background color for the control bar controlBarWidget.setStyleSheet("background-color: #D8DEE9; border: none;")
# Add left margin (same size as sizeGrip) using layout margins controlBarLayout.setContentsMargins(sizeGripSize, 0, 0, 0) # This controls the left margin
# Add stretch before the buttons to center them controlBarLayout.addStretch()
for iconPath, tooltip in controls: button = self.createControlButton(iconPath, tooltip, buttonHeight) controlBarLayout.addWidget(button)
# Add stretch after the buttons to center them controlBarLayout.addStretch()
# Add the QSizeGrip to the control bar (right-aligned) sizeGrip = QSizeGrip(self) controlBarLayout.addWidget(sizeGrip, 0, Qt.AlignRight | Qt.AlignBottom)
def toggleCommandBar(self): """Toggle visibility of the command bar and adjust window size accordingly.""" terminal_visible = self.commandBar.isVisible() self.commandBar.setVisible(not terminal_visible)
# Resize the window to accommodate the command bar self.resize(self.width(), self.height() + (30 if not terminal_visible else -30))
def processCommand(self): """Process the command entered in the command bar.""" command = self.commandBar.text() self.commandBar.clear()
def mousePressEvent(self, event: QMouseEvent): """Enable dragging of the window.""" if event.button() == Qt.LeftButton: self._dragging = True self._drag_position = event.globalPosition().toPoint() event.accept()
def mouseMoveEvent(self, event: QMouseEvent): """Handle dragging of the window.""" if self._dragging: delta = event.globalPosition().toPoint() - self._drag_position self.move(self.pos() + delta) self._drag_position = event.globalPosition().toPoint() event.accept()
def toggleMaximizeRestore(self): """Toggle between maximize and restore window states.""" if self.isMaximized(): self.showNormal() else: self.showMaximized()
def toggleFileExplorer(self): """Toggle the visibility of the file explorer widget.""" self.fileExplorerWidget.setVisible(not self.fileExplorerWidget.isVisible())
# Adjust window height if necessary if self.fileExplorerWidget.isVisible(): self.resize(self.width(), self.height() + 150) # Increase height to accommodate file explorer else: self.resize(self.width(), self.height() - 150) # Decrease height when hidden
def togglePlaylist(self): """Toggle the visibility of the playlist widget.""" self.playlistWidget.setVisible(not self.playlistWidget.isVisible())
# Adjust window height if necessary if self.playlistWidget.isVisible(): self.resize(self.width(), self.height() + 150) # Increase height to accommodate playlist else: self.resize(self.width(), self.height() - 150) # Decrease height when hidden
def processCommand(self): """Process the command entered in the command bar.""" command = self.commandBar.text().strip() if command == "f": self.toggleFileExplorer() elif command == "p": self.togglePlaylist()
[/code] код со скругленными углами: [code]mport sys from PySide6.QtCore import Qt, QSize, QRect from PySide6.QtGui import QPainter, QPainterPath, QColor from PySide6.QtWidgets import QApplication, QMainWindow, QWidget, QVBoxLayout, QPushButton
class NordMediaPlayer(QMainWindow): def __init__(self): super().__init__()
# Make the window frameless self.setWindowFlags(Qt.FramelessWindowHint) self.setAttribute(Qt.WA_TranslucentBackground) # Allow transparency for rounded corners
# Window size setup to 250x250 self.setFixedSize(250, 250)
def paintEvent(self, event): """Override paintEvent to directly paint the rounded corners with anti-aliasing.""" painter = QPainter(self)
# Enable anti-aliasing for smoother edges painter.setRenderHint(QPainter.Antialiasing)
# Create a path for the rounded rectangle path = QPainterPath() rect = QRect(0, 0, self.width(), self.height()) radius = min(self.width(), self.height()) * 0.1 # Adjust the corner radius as needed. path.addRoundedRect(rect, radius, radius)
# Set the background color (can be customized) painter.setBrush(QColor(45, 45, 48)) # Example background color (dark gray). painter.setPen(Qt.transparent) # No border for the rounded rectangle
# Fill the path with the background color (smooth rounded corners) painter.drawPath(path) # Draw the rounded shape directly
# End painting process painter.end()
def mousePressEvent(self, event): """Handle mouse press event to start dragging the window.""" self.drag_position = event.globalPosition().toPoint()
def mouseMoveEvent(self, event): """Handle mouse move event to drag the window.""" if event.buttons() == Qt.LeftButton: delta = event.globalPosition().toPoint() - self.drag_position self.move(self.pos() + delta) self.drag_position = event.globalPosition().toPoint()
def mouseReleaseEvent(self, event): """Handle mouse release event to stop dragging the window.""" self.drag_position = None
if __name__ == "__main__": app = QApplication(sys.argv) window = NordMediaPlayer() window.show() sys.exit(app.exec()) [/code] В коде 2 окно отображает закругленные углы, но в коде 1, несмотря на использование того же радиуса границы и аналогичного стиля, углы не закруглены. Я также добавил window2.setWindowFlags(Qt.FramelessWindowHint), чтобы сделать окно безрамочным, но кажется, что закругленные углы больше не применяются должным образом. Может ли кто-нибудь объяснить, почему код 1 не работает? показать закругленные углы? Нужно ли что-то настроить при использовании Qt.FramelessWindowHint? Спасибо за любую помощь! пытаюсь скруглить углы в безрамочном окне п>