Как переделать следующий код так, чтобы рамка расширялась, а не создавалась новая class…
- User
Как переделать следующий код так, чтобы рамка расширялась, а не создавалась новая class DrawingWindow(QMainWindow): def init(self, coordinates): super().init() self.setWindowTitle("Transparent Drawing Window") self.setGeometry(0, 0, QApplication.desktop().screenGeometry().width(), QApplication.desktop().screenGeometry().height()) self.setAttribute(Qt.WA_TranslucentBackground, True) self.setWindowFlags(Qt.FramelessWindowHint | Qt.WindowStaysOnTopHint)
self.painter = QPainter() self.painter.setRenderHint(QPainter.Antialiasing) self.pen_color = QColor(255, 0, 0) # Set the initial pen color to red self.pen_width = 4 # Set the initial pen width to 4 self.coordinates = coordinates # Store the coordinates for drawing rectangles self.starting_point = None def paintEvent(self, event): self.painter.begin(self) self.painter.setPen(Qt.NoPen) self.painter.setBrush(QBrush(Qt.transparent)) self.painter.drawRect(QRect(0, 0, self.width(), self.height())) # Draw a transparent background self.painter.setPen(QPen(QColor(self.pen_color), self.pen_width)) self.painter.setBrush(QBrush(Qt.transparent)) for coord in self.coordinates: x, y, width, height = coord self.painter.drawRect(x, y, width, height) # Draw rectangles using the provided coordinates self.painter.end() def mousePressEvent(self, event): self.starting_point = event.pos() def mouseMoveEvent(self, event): if self.starting_point: current_point = event.pos() x = min(self.starting_point.x(), current_point.x()) y = min(self.starting_point.y(), current_point.y()) width = abs(self.starting_point.x() - current_point.x()) height = abs(self.starting_point.y() - current_point.y()) self.coordinates.append((x, y, width, height)) self.update() def mouseReleaseEvent(self, event): self.starting_point = None - Assistant
Чтобы изменить код так, чтобы рамка расширялась вместо создания новой, нужно изменить способ рисования и обновления фигуры при движении мыши.
Вместо того, чтобы добавлять новую рамку каждый раз при перемещении мыши, нужно обновлять координаты и размер существующей рамки.
Вот как можно переделать код:
class DrawingWindow(QMainWindow): def __init__(self): super().__init__() self.setWindowTitle("Transparent Drawing Window") self.setGeometry(0, 0, QApplication.desktop().screenGeometry().width(), QApplication.desktop().screenGeometry().height()) self.setAttribute(Qt.WA_TranslucentBackground, True) self.setWindowFlags(Qt.FramelessWindowHint | Qt.WindowStaysOnTopHint) self.painter = QPainter() self.painter.setRenderHint(QPainter.Antialiasing) self.pen_color = QColor(255, 0, 0) # Set the initial pen color to red self.pen_width = 4 # Set the initial pen width to 4 self.current_rect = None # Store the current rectangle being drawn def paintEvent(self, event): self.painter.begin(self) self.painter.setPen(Qt.NoPen) self.painter.setBrush(QBrush(Qt.transparent)) self.painter.drawRect(QRect(0, 0, self.width(), self.height())) # Draw a transparent background self.painter.setPen(QPen(QColor(self.pen_color), self.pen_width)) self.painter.setBrush(QBrush(Qt.transparent)) if self.current_rect: x, y, width, height = self.current_rect self.painter.drawRect(x, y, width, height) # Draw the current rectangle self.painter.end() def mousePressEvent(self, event): self.current_rect = QRect(event.pos(), QSize(0, 0)) def mouseMoveEvent(self, event): if self.current_rect: self.current_rect.setWidth(event.x() - self.current_rect.x()) self.current_rect.setHeight(event.y() - self.current_rect.y()) self.update() def mouseReleaseEvent(self, event): self.current_rect = NoneТеперь при перемещении мыши будет обновляться размер и координаты текущей рамки, а не добавляться новая.
- User
Как следующему окну добавить функциональную рамку? import sys from PyQt5.QtWidgets import QApplication, QMainWindow from PyQt5.QtGui import QPainter, QBrush, QColor, QPen from PyQt5.QtCore import Qt, QTimer, QRect import random
class DrawingWindow(QMainWindow): def init(self, coordinates): super().init() self.setWindowTitle("Transparent Drawing Window") self.setGeometry(0, 0, QApplication.desktop().screenGeometry().width(), QApplication.desktop().screenGeometry().height()) self.setAttribute(Qt.WA_TranslucentBackground, True) self.setWindowFlags(Qt.FramelessWindowHint | Qt.WindowStaysOnTopHint)
self.painter = QPainter() self.painter.setRenderHint(QPainter.Antialiasing) self.pen_color = QColor(255, 0, 0) # Set the initial pen color to red self.pen_width = 4 # Set the initial pen width to 4 self.coordinates = coordinates # Store the coordinates for drawing rectangles self.starting_point = None def paintEvent(self, event): self.painter.begin(self) self.painter.setPen(Qt.NoPen) self.painter.setBrush(QBrush(Qt.transparent)) self.painter.drawRect(QRect(0, 0, self.width(), self.height())) # Draw a transparent background self.painter.setPen(QPen(QColor(self.pen_color), self.pen_width)) self.painter.setBrush(QBrush(Qt.transparent)) self.painter.drawRect(self.coordinates[0], self.coordinates[1], self.coordinates[2], self.coordinates[3]) # Draw rectangles using the provided coordinates self.painter.end() def mousePressEvent(self, event): self.starting_point = event.pos() def mouseMoveEvent(self, event): if self.starting_point: current_point = event.pos() if current_point.x() > self.coordinates[0] + self.coordinates[2]: self.coordinates[2] = current_point.x() - self.coordinates[0] if current_point.y() > self.coordinates[1] + self.coordinates[3]: self.coordinates[3] = current_point.y() - self.coordinates[1] if current_point.x() < self.coordinates[0] + self.coordinates[2]: self.coordinates[2] += self.coordinates[0] - current_point.x() self.coordinates[0] = current_point.x() if current_point.y() < self.coordinates[1] + self.coordinates[3]: self.coordinates[3] += self.coordinates[1] - current_point.y() self.coordinates[1] = current_point.y() self.update() self.ending_point = event.pos() def mouseReleaseEvent(self, event): '''if self.starting_point : #self.coordinates.append((x, y, width, height)) if self.ending_point.x() > self.coordinates[0] + self.coordinates[2]: self.coordinates[2] = self.ending_point.x() - self.coordinates[0] if self.ending_point.y() > self.coordinates[1] + self.coordinates[3]: self.coordinates[3] = self.ending_point.y() - self.coordinates[1] if self.ending_point.x() < self.coordinates[0] + self.coordinates[2]: self.coordinates[2] += self.coordinates[0] - self.ending_point.x() self.coordinates[0] = self.ending_point.x() if self.ending_point.y() < self.coordinates[1] + self.coordinates[3]: self.coordinates[3] += self.coordinates[1] - self.ending_point.y() self.coordinates[1] = self.ending_point.y() self.update()''' self.starting_point = None - Assistant
Для добавления функциональной рамки следующему окну можно использовать метод
setFrameShapeиsetFrameShadowиз модуляQMainWindow. Эти методы позволяют устанавливать форму и тень рамки для окна.Вот как можно изменить класс
DrawingWindow, чтобы добавить функциональную рамку:class DrawingWindow(QMainWindow): def __init__(self, coordinates): super().__init__() self.setWindowTitle("Transparent Drawing Window") self.setGeometry(0, 0, QApplication.desktop().screenGeometry().width(), QApplication.desktop().screenGeometry().height()) self.setAttribute(Qt.WA_TranslucentBackground, True) self.setWindowFlags(Qt.FramelessWindowHint | Qt.WindowStaysOnTopHint) self.painter = QPainter() self.painter.setRenderHint(QPainter.Antialiasing) self.pen_color = QColor(255, 0, 0) # Set the initial pen color to red self.pen_width = 4 # Set the initial pen width to 4 self.coordinates = coordinates # Store the coordinates for drawing rectangles self.starting_point = None self.setFrameShape(QMainWindow.Panel) # Set functional frame shape self.setFrameShadow(QMainWindow.Sunken) # Set shadow style for the frame def paintEvent(self, event): self.painter.begin(self) self.painter.setPen(Qt.NoPen) self.painter.setBrush(QBrush(Qt.transparent)) self.painter.drawRect(QRect(0, 0, self.width(), self.height())) # Draw a transparent background self.painter.setPen(QPen(QColor(self.pen_color), self.pen_width)) self.painter.setBrush(QBrush(Qt.transparent)) self.painter.drawRect(self.coordinates[0], self.coordinates[1], self.coordinates[2], self.coordinates[3]) # Draw rectangles using the provided coordinates self.painter.end() def mousePressEvent(self, event): self.starting_point = event.pos() def mouseMoveEvent(self, event): if self.starting_point: current_point = event.pos() if current_point.x() > self.coordinates[0] + self.coordinates[2]: self.coordinates[2] = current_point.x() - self.coordinates[0] if current_point.y() > self.coordinates[1] + self.coordinates[3]: self.coordinates[3] = current_point.y() - self.coordinates[1] if current_point.x() < self.coordinates[0] + self.coordinates[2]: self.coordinates[2] += self.coordinates[0] - current_point.x() self.coordinates[0] = current_point.x() if current_point.y() < self.coordinates[1] + self.coordinates[3]: self.coordinates[3] += self.coordinates[1] - current_point.y() self.coordinates[1] = current_point.y() self.update() def mouseReleaseEvent(self, event): self.starting_point = NoneТеперь у окна
DrawingWindowбудет функциональная рамка. - User
File "C:\Users\aleks\PycharmProjects\Diplom\VideoCapture.py", line 27, in init self.setTabShape(QMainWindow.Panel) # Set functional frame shape ^^^^^^^^^^^^^^^^^ AttributeError: type object 'QMainWindow' has no attribute 'Panel'
- Assistant
Извините за путаницу. В модуле
QMainWindowнет атрибутаPanel, который я использовал в примере выше.Вместо этого можно использовать атрибут
QFrame.Boxдля установки функционального стиля рамки.Вот исправленный код:
class DrawingWindow(QMainWindow): def __init__(self, coordinates): super().__init__() self.setWindowTitle("Transparent Drawing Window") self.setGeometry(0, 0, QApplication.desktop().screenGeometry().width(), QApplication.desktop().screenGeometry().height()) self.setAttribute(Qt.WA_TranslucentBackground, True) self.setWindowFlags(Qt.FramelessWindowHint | Qt.WindowStaysOnTopHint) self.painter = QPainter() self.painter.setRenderHint(QPainter.Antialiasing) self.pen_color = QColor(255, 0, 0) # Set the initial pen color to red self.pen_width = 4 # Set the initial pen width to 4 self.coordinates = coordinates # Store the coordinates for drawing rectangles self.starting_point = None self.setFrameShape(QFrame.Box) # Set functional frame shape def paintEvent(self, event): self.painter.begin(self) self.painter.setPen(Qt.NoPen) self.painter.setBrush(QBrush(Qt.transparent)) self.painter.drawRect(QRect(0, 0, self.width(), self.height())) # Draw a transparent background self.painter.setPen(QPen(QColor(self.pen_color), self.pen_width)) self.painter.setBrush(QBrush(Qt.transparent)) self.painter.drawRect(self.coordinates[0], self.coordinates[1], self.coordinates[2], self.coordinates[3]) # Draw rectangles using the provided coordinates self.painter.end() def mousePressEvent(self, event): self.starting_point = event.pos() def mouseMoveEvent(self, event): if self.starting_point: current_point = event.pos() if current_point.x() > self.coordinates[0] + self.coordinates[2]: self.coordinates[2] = current_point.x() - self.coordinates[0] if current_point.y() > self.coordinates[1] + self.coordinates[3]: self.coordinates[3] = current_point.y() - self.coordinates[1] if current_point.x() < self.coordinates[0] + self.coordinates[2]: self.coordinates[2] += self.coordinates[0] - current_point.x() self.coordinates[0] = current_point.x() if current_point.y() < self.coordinates[1] + self.coordinates[3]: self.coordinates[3] += self.coordinates[1] - current_point.y() self.coordinates[1] = current_point.y() self.update() def mouseReleaseEvent(self, event): self.starting_point = NoneТеперь вместо
QMainWindow.PanelиспользуетсяQFrame.Boxдля установки функционального стиля рамки. - User
File "C:\Users\aleks\PycharmProjects\Diplom\VideoCapture.py", line 27, in init self.setFrameShape(QFrame.Box) # Set functional frame shape ^^^^^^^^^^^^^^^^^^ AttributeError: 'DrawingWindow' object has no attribute 'setFrameShape'. Did you mean: 'setTabShape'?
- Assistant
При использовании
QFrame.Boxдля установки функционального стиля рамки, возникает ошибка, так как объект типаQMainWindowилиQFrameне имеет методаsetFrameShape.Вместо этого, для установки стиля рамки можно использовать метод
setFrameStyleу объектаQMainWindow, который позволяет устанавливать различные стили рамки.Исправленный код будет выглядеть следующим образом:
class DrawingWindow(QMainWindow): def __init__(self, coordinates): super().__init__() self.setWindowTitle("Transparent Drawing Window") self.setGeometry(0, 0, QApplication.desktop().screenGeometry().width(), QApplication.desktop().screenGeometry().height()) self.setAttribute(Qt.WA_TranslucentBackground, True) self.setWindowFlags(Qt.FramelessWindowHint | Qt.WindowStaysOnTopHint) self.painter = QPainter() self.painter.setRenderHint(QPainter.Antialiasing) self.pen_color = QColor(255, 0, 0) # Set the initial pen color to red self.pen_width = 4 # Set the initial pen width to 4 self.coordinates = coordinates # Store the coordinates for drawing rectangles self.starting_point = None self.setFrameStyle(QFrame.Box) # Set functional frame style def paintEvent(self, event): self.painter.begin(self) self.painter.setPen(Qt.NoPen) self.painter.setBrush(QBrush(Qt.transparent)) self.painter.drawRect(QRect(0, 0, self.width(), self.height())) # Draw a transparent background self.painter.setPen(QPen(QColor(self.pen_color), self.pen_width)) self.painter.setBrush(QBrush(Qt.transparent)) self.painter.drawRect(self.coordinates[0], self.coordinates[1], self.coordinates[2], self.coordinates[3]) # Draw rectangles using the provided coordinates self.painter.end() def mousePressEvent(self, event): self.starting_point = event.pos() def mouseMoveEvent(self, event): if self.starting_point: current_point = event.pos() if current_point.x() > self.coordinates[0] + self.coordinates[2]: self.coordinates[2] = current_point.x() - self.coordinates[0] if current_point.y() > self.coordinates[1] + self.coordinates[3]: self.coordinates[3] = current_point.y() - self.coordinates[1] if current_point.x() < self.coordinates[0] + self.coordinates[2]: self.coordinates[2] += self.coordinates[0] - current_point.x() self.coordinates[0] = current_point.x() if current_point.y() < self.coordinates[1] + self.coordinates[3]: self.coordinates[3] += self.coordinates[1] - current_point.y() self.coordinates[1] = current_point.y() self.update() def mouseReleaseEvent(self, event): self.starting_point = NoneТеперь рамка с функциональным стилем должна отображаться верно.
- User
File "C:\Users\aleks\PycharmProjects\Diplom\VideoCapture.py", line 27, in init self.setFrameStyle(QFrame.Box) # Set functional frame shape ^^^^^^^^^^^^^^^^^^ AttributeError: 'DrawingWindow' object has no attribute 'setFrameStyle'
- Assistant
Извините за путаницу, причиной появления ошибки является то, что объект
QMainWindowне имеет атрибутаsetFrameStyle.Однако есть способ устанавливать рамку окна с использованием CSS стилей. В PyQt5 можно использовать CSS для установки стиля рамки окна.
Вот как можно установить рамку с функциональным стилем с помощью CSS:
class DrawingWindow(QMainWindow): def __init__(self, coordinates): super().__init__() self.setWindowTitle("Transparent Drawing Window") self.setGeometry(0, 0, QApplication.desktop().screenGeometry().width(), QApplication.desktop().screenGeometry().height()) self.setAttribute(Qt.WA_TranslucentBackground, True) self.setWindowFlags(Qt.FramelessWindowHint | Qt.WindowStaysOnTopHint) self.setStyleSheet("QMainWindow { border: 2px solid black; border-radius: 10px; }") self.painter = QPainter() self.painter.setRenderHint(QPainter.Antialiasing) self.pen_color = QColor(255, 0, 0) # Set the initial pen color to red self.pen_width = 4 # Set the initial pen width to 4 self.coordinates = coordinates # Store the coordinates for drawing rectangles self.starting_point = None def paintEvent(self, event): self.painter.begin(self) self.painter.setPen(Qt.NoPen) self.painter.setBrush(QBrush(Qt.transparent)) self.painter.drawRect(QRect(0, 0, self.width(), self.height())) # Draw a transparent background self.painter.setPen(QPen(QColor(self.pen_color), self.pen_width)) self.painter.setBrush(QBrush(Qt.transparent)) self.painter.drawRect(self.coordinates[0], self.coordinates[1], self.coordinates[2], self.coordinates[3]) # Draw rectangles using the provided coordinates self.painter.end() def mousePressEvent(self, event): self.starting_point = event.pos() def mouseMoveEvent(self, event): if self.starting_point: current_point = event.pos() if current_point.x() > self.coordinates[0] + self.coordinates[2]: self.coordinates[2] = current_point.x() - self.coordinates[0] if current_point.y() > self.coordinates[1] + self.coordinates[3]: self.coordinates[3] = current_point.y() - self.coordinates[1] if current_point.x() < self.coordinates[0] + self.coordinates[2]: self.coordinates[2] += self.coordinates[0] - current_point.x() self.coordinates[0] = current_point.x() if current_point.y() < self.coordinates[1] + self.coordinates[3]: self.coordinates[3] += self.coordinates[1] - current_point.y() self.coordinates[1] = current_point.y() self.update() def mouseReleaseEvent(self, event): self.starting_point = NoneТеперь рамка с функциональным стилем должна отображаться с помощью CSS.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.