There is a roundrect on graphicsscene and i am trying to move but when it goes 'end of the' any side of screen it goes out of the screen but it should not go outside of the screen it should move like a game callled "SNAKE XENZIA"
from PyQt5.QtWidgets import QApplication, QWidget, QDesktopWidget, QGraphicsView, QGraphicsScene, QGraphicsItem
from PyQt5.QtCore import Qt, QRectF
from PyQt5.QtGui import QBrush, QColor
import sys
class GraphicsItem(QGraphicsItem):
def __init__(self, parent):
super().__init__()
self.setFlag(QGraphicsItem.ItemIsFocusable)
self.setFocus()
self.screenSize = QDesktopWidget().screenGeometry(0)
self.screenHeight = self.screenSize.height()
self.screenWidth = self.screenSize.width()
def boundingRect(self):
return QRectF(0, 0, self.screenWidth, self.screenHeight)
def paint(self, painter, option, widget):
painter.setBrush(QBrush(Qt.magenta))
painter.drawRoundedRect(10, 10, 70, 70, 5, 5)
# painter.drawEllipse(10, 100, 70, 70)
def keyPressEvent(self, event):
if event.key() == Qt.Key_Right:
self.moveBy(10, 0)
elif event.key() == Qt.Key_Left:
self.moveBy(-10, 0)
elif event.key() == Qt.Key_Down:
self.moveBy(0, 10)
elif event.key() == Qt.Key_Up:
self.moveBy(0, -10)
self.update()
class GraphicsScene(QGraphicsScene):
def __init__(self, parent):
super().__init__(parent=parent)
graphicsitem = GraphicsItem(self)
self.addItem(graphicsitem)
self.setBackgroundBrush(QColor(10, 155, 79))
self.screenSize = QDesktopWidget().screenGeometry(0)
self.screenHeight = self.screenSize.height()
self.screenWidth = self.screenSize.width()
class GraphicsView(QGraphicsView):
def __init__(self, parent):
super().__init__(parent=parent)
graphicsscene = GraphicsScene(self)
self.screenSize = QDesktopWidget().screenGeometry(0)
self.screenHeight = self.screenSize.height()
self.screenWidth = self.screenSize.width()
self.setGeometry(0, 0, self.screenWidth, self.screenHeight)
self.setScene(graphicsscene)
self.show()
class Widget(QWidget):
def __init__(self):
super().__init__()
graphicsview = GraphicsView(self)
self.screenSize = QDesktopWidget().screenGeometry(0)
self.screenHeight = self.screenSize.height()
self.screenWidth = self.screenSize.width()
self.initUI()
def initUI(self):
self.setWindowTitle("Graphics View")
self.setGeometry(0, 0, self.screenWidth, self.screenHeight)
self.show()
if __name__ == "__main__":
app = QApplication(sys.argv)
widget = Widget()
sys.exit(app.exec_())
Try it:
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QDesktopWidget, QGraphicsView, QGraphicsScene, QGraphicsItem
from PyQt5.QtCore import Qt, QRectF
from PyQt5.QtGui import QBrush, QColor
class GraphicsItem(QGraphicsItem):
def __init__(self, parent):
super().__init__()
self.setFlag(QGraphicsItem.ItemIsFocusable)
self.setFocus()
self.screenSize = QDesktopWidget().screenGeometry(0)
self.screenHeight = self.screenSize.height()
self.screenWidth = self.screenSize.width()
def boundingRect(self):
self.posX = self.pos().x() # +++
self.posY = self.pos().y() # +++
return QRectF(0, 0, self.screenWidth, self.screenHeight)
def paint(self, painter, option, widget):
painter.setBrush(QBrush(Qt.magenta))
painter.drawRoundedRect(10, 10, 70, 70, 5, 5)
# painter.drawEllipse(10, 100, 70, 70)
def keyPressEvent(self, event):
if event.key() == Qt.Key_Right:
# self.moveBy(10, 0)
if self.posX >= 1270: self.moveBy(-1270, 0) # +++
else: self.moveBy(10, 0) # +++
elif event.key() == Qt.Key_Left:
# self.moveBy(-10, 0)
if self.posX > 0: self.moveBy(-10, 0) # +++
else: self.moveBy(1270, 0) # +++
elif event.key() == Qt.Key_Down:
# self.moveBy(0, 10)
if self.posY >= 670: self.moveBy(0, -670) # +++
else: self.moveBy(0, 10) # +++
elif event.key() == Qt.Key_Up:
# self.moveBy(0, -10)
if self.posY > 0: self.moveBy(0, -10) # +++
else: self.moveBy(0, 670) # +++
# self.update()
class GraphicsScene(QGraphicsScene):
def __init__(self, parent):
super().__init__(parent=parent)
graphicsitem = GraphicsItem(self)
self.addItem(graphicsitem)
self.setBackgroundBrush(QColor(10, 155, 79))
self.screenSize = QDesktopWidget().screenGeometry(0)
self.screenHeight = self.screenSize.height()
self.screenWidth = self.screenSize.width()
class GraphicsView(QGraphicsView):
def __init__(self, parent):
super().__init__(parent=parent)
graphicsscene = GraphicsScene(self)
self.screenSize = QDesktopWidget().screenGeometry(0)
self.screenHeight = self.screenSize.height()
self.screenWidth = self.screenSize.width()
self.setGeometry(0, 0, self.screenWidth, self.screenHeight)
self.setScene(graphicsscene)
# self.show()
class Widget(QWidget):
def __init__(self):
super().__init__()
graphicsview = GraphicsView(self)
self.screenSize = QDesktopWidget().screenGeometry(0)
self.screenHeight = self.screenSize.height()
self.screenWidth = self.screenSize.width()
self.initUI()
self.setFixedSize(self.screenWidth, self.screenHeight) # +++
def initUI(self):
self.setWindowTitle("Graphics View")
self.setGeometry(0, 0, self.screenWidth, self.screenHeight)
# self.show()
if __name__ == "__main__":
app = QApplication(sys.argv)
widget = Widget()
widget.show()
sys.exit(app.exec_())
Related
I am trying to use PyQt (PySide6) to draw a Pipeline network like in this example gif
[1]: https://i.stack.imgur.com/uQsRg.gif
I know i have to use the QGraphicsView class with QGraphicsScene to draw elements in the screen.
What i dont know how to do is how to handle all the mouse click and move events as well as having Ports on each side of the pipe to be able to attach other pipes/elements to pipes.
i also have to be able to double click on elements to configure them.
Is there any good documentation where i can learn how to achieve this ? or any tutorials ?
Thank you.
import sys
from PySide6.QtWidgets import (
QApplication,
QMainWindow,
QGraphicsView,
QGraphicsScene,
)
from PySide6.QtGui import QAction
from PySide6.QtCore import Qt
class GraphicsScene(QGraphicsScene):
def __init__(self):
super().__init__()
def mousePressEvent(self, event) -> None:
if event.button() == Qt.LeftButton:
print("Left button pressed")
pos_x = event.scenePos().x()
pos_y = event.scenePos().y()
print(f"Position: {pos_x}, {pos_y}")
class GraphicsView(QGraphicsView):
def __init__(self):
super().__init__()
self.scene = self.setScene(GraphicsScene())
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
"""Set up the application's GUI."""
self.setMinimumSize(450, 350)
self.setWindowTitle("Main Window")
self.setup_main_window()
self.create_actions()
self.create_menu()
self.show()
def setup_main_window(self):
"""Create and arrange widgets in the main window."""
self.setCentralWidget(GraphicsView())
def create_actions(self):
"""Create the application's menu actions."""
# Create actions for File menu
self.quit_act = QAction("&Quit")
self.quit_act.setShortcut("Ctrl+Q")
self.quit_act.triggered.connect(self.close)
def create_menu(self):
"""Create the application's menu bar."""
self.menuBar().setNativeMenuBar(False)
# Create file menu and add actions
file_menu = self.menuBar().addMenu("File")
file_menu.addAction(self.quit_act)
if __name__ == "__main__":
app = QApplication(sys.argv)
window = MainWindow()
sys.exit(app.exec())
EDIT/UPDATE :
Here's a solution. Thanks for the help
import sys
from PySide6.QtWidgets import (
QApplication,
QMainWindow,
QGraphicsView,
QGraphicsScene,
QGraphicsEllipseItem,
)
from PySide6.QtGui import QPainterPath, QTransform, QPen, QBrush, QColor, QPainter
from PySide6.QtCore import Qt
PORT_PEN_COLOR = "#000000"
PORT_BRUSH_COLOR = "#ebebeb"
EDGE_PEN_COLOR = "#474747"
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setGeometry(0, 0, 800, 600)
self.setCentralWidget(GraphicsView())
self.show()
class GraphicsView(QGraphicsView):
def __init__(self, parent=None):
super().__init__(parent)
self.setMouseTracking(True)
self.setScene(GraphicsScene())
self.setRenderHint(QPainter.RenderHint.Antialiasing)
class GraphicsScene(QGraphicsScene):
def __init__(self, parent=None):
super().__init__(parent)
self.setSceneRect(-10000, -10000, 20000, 20000)
self._port_pen = QPen(QColor(PORT_PEN_COLOR))
self._port_brush = QBrush(QColor(PORT_BRUSH_COLOR))
self._edge_pen = QPen(QColor(EDGE_PEN_COLOR))
self._edge_pen.setWidth(4)
def mousePressEvent(self, event):
clicked_item = self.itemAt(event.scenePos(), QTransform())
if event.buttons() == Qt.MouseButton.LeftButton:
if clicked_item is not None:
# edge item
pos = clicked_item.scenePos()
pos.setX(pos.x() + 6)
pos.setY(pos.y() + 6)
self.edge = self.addPath(QPainterPath())
self.edge.setPen(self._edge_pen)
self.start_pos = pos
self.end_pos = self.start_pos
self.update_path()
else:
x = event.scenePos().x()
y = event.scenePos().y()
# port item
start_port = Ellipse()
start_port.setPos(x - 6, y - 6)
start_port.setPen(self._port_pen)
start_port.setBrush(self._port_brush)
start_port.setZValue(10000.0)
self.addItem(start_port)
# edge item
self.edge = self.addPath(QPainterPath())
self.edge.setPen(self._edge_pen)
self.start_pos = event.scenePos()
self.end_pos = self.start_pos
self.update_path()
def mouseMoveEvent(self, event):
if event.buttons() == Qt.MouseButton.LeftButton:
print(f"moving, x : {event.scenePos().x()}, y : {event.scenePos().y()}")
self.end_pos = event.scenePos()
try:
self.update_path()
except AttributeError:
pass
def mouseReleaseEvent(self, event) -> None:
released_item = self.itemAt(event.scenePos(), QTransform())
if event.button() == Qt.MouseButton.LeftButton:
if released_item is not None and released_item.type() != 2:
self.end_pos = released_item.scenePos()
self.end_pos.setX(self.end_pos.x() + 6)
self.end_pos.setY(self.end_pos.y() + 6)
if not self.start_pos.isNull() and not self.end_pos.isNull():
path = QPainterPath()
path.moveTo(self.start_pos.x() - 1, self.start_pos.y() - 1)
path.lineTo(self.end_pos)
self.edge.setPath(path)
else:
x = event.scenePos().x() + 1
y = event.scenePos().y() + 1
end_port = QGraphicsEllipseItem(0, 0, 10, 10)
end_port.setPos(x - 6, y - 6)
end_port.setPen(self._port_pen)
end_port.setBrush(self._port_brush)
end_port.setZValue(10000.0)
self.addItem(end_port)
def update_path(self):
if not self.start_pos.isNull() and not self.end_pos.isNull():
path = QPainterPath()
path.moveTo(self.start_pos.x() - 1, self.start_pos.y() - 1)
path.lineTo(self.end_pos)
self.edge.setPath(path)
class Ellipse(QGraphicsEllipseItem):
def __init__(self):
super().__init__()
self.setRect(0, 0, 10, 10)
if __name__ == "__main__":
app = QApplication(sys.argv)
win = MainWindow()
sys.exit(app.exec())
It may need to write all code on your own - check button, check if there is object in small distance, remeber this object, draw this object as selected (with some extra color), update object position when move mouse, redraw all objects, etc. So it may need some list to keep all objects, search if mouse is near of one of object on list, update objects on list, use list to redraw objects on screen (in new positions)
Minimal code which use left click to add item (rectangle), and right click to delete it.
EDIT:
I found out that scene has function .items() to access all items and I don't have to use own list objects for this.
import sys
from PySide6.QtWidgets import (
QApplication,
QMainWindow,
QGraphicsView,
QGraphicsScene,
QGraphicsRectItem,
)
from PySide6.QtGui import QAction
from PySide6.QtCore import Qt
#objects = []
class GraphicsScene(QGraphicsScene):
def __init__(self, parent=None):
super().__init__(parent)
self.setSceneRect(-100, -100, 200, 200)
def mousePressEvent(self, event) -> None:
if event.button() == Qt.LeftButton:
#print("Left button pressed")
x = event.scenePos().x()
y = event.scenePos().y()
#print(f"Position: {x}, {y}")
rectitem = QGraphicsRectItem(0, 0, 10, 10)
# set center of rectangle in mouse position
rectitem.setPos(x-5, y-5)
self.addItem(rectitem)
#objects.append(rectitem)
elif event.button() == Qt.RightButton:
#print("Right button pressed")
x = event.scenePos().x()
y = event.scenePos().y()
#print(f"Position: {x}, {y}")
#for item in objects:
for item in self.items():
pos = item.pos()
if abs(x-pos.x()) < 10 and abs(y-pos.y()) < 10:
print('selected:', item)
self.removeItem(item)
#objects.remove(item)
break
class GraphicsView(QGraphicsView):
def __init__(self):
super().__init__()
self.scene = self.setScene(GraphicsScene())
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
"""Set up the application's GUI."""
self.setMinimumSize(450, 350)
self.setWindowTitle("Main Window")
self.setup_main_window()
self.create_actions()
self.create_menu()
self.show()
def setup_main_window(self):
"""Create and arrange widgets in the main window."""
self.setCentralWidget(GraphicsView())
def create_actions(self):
"""Create the application's menu actions."""
# Create actions for File menu
self.quit_act = QAction("&Quit")
self.quit_act.setShortcut("Ctrl+Q")
self.quit_act.triggered.connect(self.close)
def create_menu(self):
"""Create the application's menu bar."""
self.menuBar().setNativeMenuBar(False)
# Create file menu and add actions
file_menu = self.menuBar().addMenu("File")
file_menu.addAction(self.quit_act)
if __name__ == "__main__":
app = QApplication(sys.argv)
window = MainWindow()
sys.exit(app.exec_())
EDIT:
Example which use
left click to add rectangle (white background, black border)
first right click to select rectangle (red background)
second right click to put selected rectangle in new place (white background, black border)
import sys
from PySide6.QtWidgets import (
QApplication,
QMainWindow,
QGraphicsView,
QGraphicsScene,
QGraphicsRectItem,
)
from PySide6.QtGui import QAction
from PySide6.QtCore import Qt
from PySide6.QtGui import QColor, QPen, QBrush
class GraphicsScene(QGraphicsScene):
def __init__(self, parent=None):
super().__init__(parent)
self.setSceneRect(-100, -100, 200, 200)
self.selected = []
def mousePressEvent(self, event) -> None:
if event.button() == Qt.LeftButton:
#print("Left button pressed")
x = event.scenePos().x()
y = event.scenePos().y()
#print(f"Position: {x}, {y}")
rectitem = QGraphicsRectItem(0, 0, 10, 10)
# set center of rectangle in mouse position
rectitem.setPos(x-5, y-5)
rectitem.setPen(QPen(QColor(0, 0, 0), 1.0, Qt.SolidLine))
rectitem.setBrush(QBrush(QColor(255, 255, 255, 255)))
self.addItem(rectitem)
elif event.button() == Qt.RightButton:
#print("Right button pressed")
x = event.scenePos().x()
y = event.scenePos().y()
#print(f"Position: {x}, {y}")
if self.selected:
print('moved')
for item in self.selected:
item.setPos(x-5, y-5)
item.setPen(QPen(QColor(0, 0, 0), 1.0, Qt.SolidLine))
item.setBrush(QBrush(QColor(255, 255, 255, 255)))
self.selected.clear()
else:
for item in self.items():
pos = item.pos()
if abs(x-pos.x()) < 10 and abs(y-pos.y()) < 10:
print('selected:', item)
self.selected.append(item)
item.setPen(QPen(QColor(255, 0, 0), 1.0, Qt.SolidLine))
item.setBrush(QBrush(QColor(255, 0, 0, 255)))
class GraphicsView(QGraphicsView):
def __init__(self):
super().__init__()
self.scene = self.setScene(GraphicsScene())
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
"""Set up the application's GUI."""
self.setMinimumSize(450, 350)
self.setWindowTitle("Main Window")
self.setup_main_window()
self.create_actions()
self.create_menu()
self.show()
def setup_main_window(self):
"""Create and arrange widgets in the main window."""
self.setCentralWidget(GraphicsView())
def create_actions(self):
"""Create the application's menu actions."""
# Create actions for File menu
self.quit_act = QAction("&Quit")
self.quit_act.setShortcut("Ctrl+Q")
self.quit_act.triggered.connect(self.close)
def create_menu(self):
"""Create the application's menu bar."""
self.menuBar().setNativeMenuBar(False)
# Create file menu and add actions
file_menu = self.menuBar().addMenu("File")
file_menu.addAction(self.quit_act)
if __name__ == "__main__":
app = QApplication(sys.argv)
window = MainWindow()
sys.exit(app.exec_())
EDIT:
Version which uses mouseMoveEvent and mouseReleaseEvent to drag rect (keeping right click)
Based on code in answer to pyqt add rectangle in Qgraphicsscene
import sys
from PySide6.QtWidgets import (
QApplication,
QMainWindow,
QGraphicsView,
QGraphicsScene,
QGraphicsRectItem,
QGraphicsItem,
)
from PySide6.QtGui import QAction
from PySide6.QtCore import Qt
from PySide6.QtGui import QColor, QPen, QBrush, QTransform
class GraphicsScene(QGraphicsScene):
def __init__(self, parent=None):
super().__init__(parent)
self.setSceneRect(-100, -100, 200, 200)
self.selected = None
self.selected_offset_x = 0
self.selected_offset_y = 0
def mousePressEvent(self, event) -> None:
if event.button() == Qt.LeftButton:
x = event.scenePos().x()
y = event.scenePos().y()
rectitem = QGraphicsRectItem(0, 0, 10, 10)
rectitem.setPos(x-5, y-5)
rectitem.setPen(QPen(QColor(0, 0, 0), 1.0, Qt.SolidLine))
rectitem.setBrush(QBrush(QColor(255, 255, 255, 255)))
#rectitem.setFlag(QGraphicsItem.ItemIsMovable, True)
self.addItem(rectitem)
elif event.button() == Qt.RightButton:
x = event.scenePos().x()
y = event.scenePos().y()
if not self.selected:
item = self.itemAt(event.scenePos(), QTransform())
#print(item)
if item:
print('selected:', item)
self.selected = item
self.selected.setBrush(QBrush(QColor(255, 0, 0, 255)))
self.selected_offset_x = x - item.pos().x()
self.selected_offset_y = y - item.pos().y()
#self.selected_offset_x = 5 # rect_width/2 # to keep center of rect
#self.selected_offset_y = 5 # rect_height/2 # to keep center of rect
#super().mousePressEvent(event)
def mouseMoveEvent(self, event):
#print('move:', event.button())
#print('move:', event.buttons())
if event.buttons() == Qt.RightButton: # `buttons()` instead of `button()`
if self.selected:
print('moved')
x = event.scenePos().x()
y = event.scenePos().y()
self.selected.setPos(x-self.selected_offset_x, y-self.selected_offset_y)
#super().mouseMoveEvent(event)
def mouseReleaseEvent(self, event):
#print('release:', event.button())
#print('release:', event.buttons())
if event.button() == Qt.RightButton:
if self.selected:
print('released')
self.selected.setBrush(QBrush(QColor(255, 255, 255, 255)))
self.selected = None
#super().mouseReleaseEvent(event)
class GraphicsView(QGraphicsView):
def __init__(self):
super().__init__()
self.scene = self.setScene(GraphicsScene())
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
"""Set up the application's GUI."""
self.setMinimumSize(450, 350)
self.setWindowTitle("Main Window")
self.setup_main_window()
self.create_actions()
self.create_menu()
self.show()
def setup_main_window(self):
"""Create and arrange widgets in the main window."""
self.setCentralWidget(GraphicsView())
def create_actions(self):
"""Create the application's menu actions."""
# Create actions for File menu
self.quit_act = QAction("&Quit")
self.quit_act.setShortcut("Ctrl+Q")
self.quit_act.triggered.connect(self.close)
def create_menu(self):
"""Create the application's menu bar."""
self.menuBar().setNativeMenuBar(False)
# Create file menu and add actions
file_menu = self.menuBar().addMenu("File")
file_menu.addAction(self.quit_act)
if __name__ == "__main__":
app = QApplication(sys.argv)
window = MainWindow()
sys.exit(app.exec_())
I was thinking about changing color when mouse hover item (using mouseMoveEvent) but at this moment I don't have it.
I found this code on here:
https://python.tutorialink.com/drawing-straight-line-between-two-points-using-qpainterpath/
which lets you create a line with mousePress and move events
import sys
from PySide6.QtWidgets import (
QApplication,
QMainWindow,
QGraphicsView,
QGraphicsScene,
)
from PySide6.QtGui import QAction, QPainterPath
from PySide6.QtCore import Qt, QPointF
class GraphicsScene(QGraphicsScene):
def __init__(self, *args, **kwargs):
super(GraphicsScene, self).__init__(*args, **kwargs)
self.path_item = self.addPath(QPainterPath())
self.start_point = QPointF()
self.end_point = QPointF()
def mousePressEvent(self, event):
self.start_point = event.scenePos()
self.end_point = self.start_point
self.update_path()
super().mousePressEvent(event)
def mouseMoveEvent(self, event):
if event.buttons() & Qt.LeftButton:
self.end_point = event.scenePos()
self.update_path()
super(GraphicsScene, self).mouseMoveEvent(event)
def mouseReleaseEvent(self, event):
self.end_point = event.scenePos()
self.update_path()
super(GraphicsScene, self).mouseReleaseEvent(event)
def update_path(self):
if not self.start_point.isNull() and not self.end_point.isNull():
path = QPainterPath()
path.moveTo(self.start_point)
path.lineTo(self.end_point)
self.path_item.setPath(path)
class GraphicsView(QGraphicsView):
def __init__(self):
super().__init__()
self.scene = self.setScene(GraphicsScene())
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
"""Set up the application's GUI."""
self.setMinimumSize(450, 350)
self.setWindowTitle("Main Window")
self.setup_main_window()
self.create_actions()
self.create_menu()
self.show()
def setup_main_window(self):
"""Create and arrange widgets in the main window."""
self.setCentralWidget(GraphicsView())
def create_actions(self):
"""Create the application's menu actions."""
# Create actions for File menu
self.quit_act = QAction("&Quit")
self.quit_act.setShortcut("Ctrl+Q")
self.quit_act.triggered.connect(self.close)
def create_menu(self):
"""Create the application's menu bar."""
self.menuBar().setNativeMenuBar(False)
# Create file menu and add actions
file_menu = self.menuBar().addMenu("File")
file_menu.addAction(self.quit_act)
if __name__ == "__main__":
app = QApplication(sys.argv)
window = MainWindow()
sys.exit(app.exec_())
EDIT :
I combined it with Furas's code and got this
import sys
from PySide6.QtWidgets import (
QApplication,
QMainWindow,
QGraphicsView,
QGraphicsScene,
QGraphicsRectItem,
)
from PySide6.QtGui import QAction, QPainterPath
from PySide6.QtCore import Qt
from PySide6.QtGui import QColor, QPen, QBrush, QTransform
class GraphicsScene(QGraphicsScene):
def __init__(self, parent=None):
super().__init__(parent)
self.setSceneRect(-100, -100, 200, 200)
self.selected = None
self.selected_offset_x = 0
self.selected_offset_y = 0
def mousePressEvent(self, event) -> None:
if event.button() == Qt.LeftButton:
x = event.scenePos().x()
y = event.scenePos().y()
# rectangle
rectitem = QGraphicsRectItem(0, 0, 10, 10)
rectitem.setPos(x - 5, y - 5)
rectitem.setPen(QPen(QColor(0, 0, 0), 1.0, Qt.SolidLine))
rectitem.setBrush(QBrush(QColor(255, 255, 255, 255)))
# rectitem.setFlag(QGraphicsItem.ItemIsMovable, True)
# Line
self.path_item = self.addPath(QPainterPath())
self.start_point = event.scenePos()
self.end_point = self.start_point
self.update_path()
self.addItem(rectitem)
elif event.button() == Qt.RightButton:
x = event.scenePos().x()
y = event.scenePos().y()
if not self.selected:
item = self.itemAt(event.scenePos(), QTransform())
# print(item)
if item:
print("selected:", item)
self.selected = item
self.selected.setBrush(QBrush(QColor(255, 0, 0, 255)))
self.selected_offset_x = x - item.pos().x()
self.selected_offset_y = y - item.pos().y()
# self.selected_offset_x = 5 # rect_width/2 # to keep center of rect
# self.selected_offset_y = 5 # rect_height/2 # to keep center of rect
# super().mousePressEvent(event)
def mouseMoveEvent(self, event):
# print('move:', event.button())
# print('move:', event.buttons())
if event.buttons() == Qt.RightButton: # `buttons()` instead of `button()`
if self.selected:
print("moved")
x = event.scenePos().x()
y = event.scenePos().y()
self.selected.setPos(
x - self.selected_offset_x, y - self.selected_offset_y
)
elif event.buttons() == Qt.LeftButton:
self.end_point = event.scenePos()
self.update_path()
# super().mouseMoveEvent(event)
def mouseReleaseEvent(self, event):
# print('release:', event.button())
# print('release:', event.buttons())
if event.button() == Qt.RightButton:
if self.selected:
print("released")
self.selected.setBrush(QBrush(QColor(255, 255, 255, 255)))
self.selected = None
elif event.button() == Qt.LeftButton:
self.end_point = event.scenePos()
x = event.scenePos().x()
y = event.scenePos().y()
rectitem = QGraphicsRectItem(0, 0, 10, 10)
rectitem.setPos(x - 5, y - 5)
rectitem.setPen(QPen(QColor(0, 0, 0), 1.0, Qt.SolidLine))
rectitem.setBrush(QBrush(QColor(255, 255, 255, 255)))
self.addItem(rectitem)
self.update_path()
# super().mouseReleaseEvent(event)
def update_path(self):
if not self.start_point.isNull() and not self.end_point.isNull():
path = QPainterPath()
path.moveTo(self.start_point)
path.lineTo(self.end_point)
self.path_item.setPath(path)
class GraphicsView(QGraphicsView):
def __init__(self):
super().__init__()
self.scene = self.setScene(GraphicsScene())
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
"""Set up the application's GUI."""
self.setMinimumSize(450, 350)
self.setWindowTitle("Main Window")
self.setup_main_window()
self.create_actions()
self.create_menu()
self.show()
def setup_main_window(self):
"""Create and arrange widgets in the main window."""
self.setCentralWidget(GraphicsView())
def create_actions(self):
"""Create the application's menu actions."""
# Create actions for File menu
self.quit_act = QAction("&Quit")
self.quit_act.setShortcut("Ctrl+Q")
self.quit_act.triggered.connect(self.close)
def create_menu(self):
"""Create the application's menu bar."""
self.menuBar().setNativeMenuBar(False)
# Create file menu and add actions
file_menu = self.menuBar().addMenu("File")
file_menu.addAction(self.quit_act)
if __name__ == "__main__":
app = QApplication(sys.argv)
window = MainWindow()
sys.exit(app.exec_())
I am trying to model a chess board and i want the pawn GraphicsItem object to be dropped in the center of the case GraphicsItem object .
i only implemented a mouseRelease event for the pawn object, it checks the list of items in the position, if a case is present i drop the pawn at the case position .
now when trying it in the window it works fine for the first move, but after that when i try to move the pawn it goes back to its original position i can still move it but its not under the mouse cursor
here is the code:
import sys
from PyQt5.QtWidgets import (QApplication, QWidget, QGridLayout,
QGraphicsView, QGraphicsScene, QGraphicsItem)
from PyQt5.QtGui import QPen, QBrush, QTransform
from PyQt5.QtCore import Qt, QRectF, QPointF
class Pawn(QGraphicsItem):
def __init__(self, parent = None):
super().__init__(parent)
self.setFlag(QGraphicsItem.ItemIsMovable)
self.setPos(0, 0)
self.setZValue(1)
self.originalPos = self.scenePos()
def paint(self, painter, options, widget):
painter.setBrush(Qt.white)
painter.drawEllipse(0, 0, 30, 30)
def boundingRect(self):
return QRectF(0, 0, 30, 30)
def mouseReleaseEvent(self, event):
dropPos = self.mapToScene(event.pos())
dropCase = None
for item in self.scene().items(dropPos.x(), dropPos.y(), 0.0001, 0.0001,
Qt.IntersectsItemShape,
Qt.AscendingOrder):
if isinstance(item, Case):
dropCase = item
if dropCase:
newP = dropCase.scenePos()
self.setPos(newP)
self.originalPos = newP
else:
self.setPos(self.originalPos)
class Case(QGraphicsItem):
def __init__(self, parent = None):
super().__init__(parent)
self.setPos(100, 0)
self.setZValue(0)
def paint(self, painter, options, widget):
painter.setPen(Qt.black)
painter.setBrush(Qt.black)
painter.drawRect(0, 0, 40, 40)
def boundingRect(self):
return QRectF(0, 0, 40, 40)
def getCenter(self):
x, y = self.scenePos().x() + 10, self.scenePos().y() + 10
return QPointF(x, y)
class MainWin(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
scene = QGraphicsScene()
view = QGraphicsView(scene, self)
view.setGeometry(0, 0, 290, 290)
case = Case()
pawn = Pawn()
scene.addItem(case)
scene.addItem(pawn)
self.setWindowTitle('doodling')
self.setGeometry(200, 200, 300, 300)
self.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
window = MainWin()
sys.exit(app.exec_())
I did not implement the mouseMoveEvent as i confused it with hover behaviour.
this code works as intended
from PyQt5.QtWidgets import (QApplication, QWidget, QGridLayout,
QGraphicsView, QGraphicsScene, QGraphicsItem)
from PyQt5.QtGui import QPen, QBrush, QTransform
from PyQt5.QtCore import Qt, QRectF, QPointF
class Pawn(QGraphicsItem):
def __init__(self, parent = None):
super().__init__(parent)
self.setFlag(QGraphicsItem.ItemIsMovable)
self.setPos(0, 0)
self.setZValue(1)
self.originalPos = self.scenePos()
def paint(self, painter, options, widget):
painter.setBrush(Qt.white)
painter.drawEllipse(0, 0, 30, 30)
def boundingRect(self):
return QRectF(0, 0, 30, 30)
def mouseMoveEvent(self, event):
movePos = self.mapToScene(event.pos())
self.setPos(movePos.x(), movePos.y())
def mouseReleaseEvent(self, event):
dropPos = self.mapToScene(event.pos())
dropCase = None
for item in self.scene().items(dropPos.x(), dropPos.y(), 0.0001, 0.0001,
Qt.IntersectsItemShape,
Qt.AscendingOrder):
if isinstance(item, Case):
dropCase = item
if dropCase:
newP = dropCase.scenePos()
self.setPos(newP)
self.originalPos = newP
else:
self.setPos(self.originalPos)
class Case(QGraphicsItem):
def __init__(self, x_coord, y_coord, parent = None):
super().__init__(parent)
self.setPos(x_coord, y_coord)
self.setZValue(0)
def paint(self, painter, options, widget):
painter.setPen(Qt.black)
painter.setBrush(Qt.black)
painter.drawRect(0, 0, 40, 40)
def boundingRect(self):
return QRectF(0, 0, 40, 40)
def getCenter(self):
x, y = self.scenePos().x() + 10, self.scenePos().y() + 10
return QPointF(x, y)
class MainWin(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
scene = QGraphicsScene()
view = QGraphicsView(scene, self)
view.setGeometry(0, 0, 290, 290)
case1 = Case(-100, 0)
case2 = Case(100, 0)
pawn = Pawn()
scene.addItem(case1)
scene.addItem(case2)
scene.addItem(pawn)
self.setWindowTitle('doodling')
self.setGeometry(200, 200, 300, 300)
self.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
window = MainWin()
sys.exit(app.exec_())
In the program below, load the background image and paint it on it.
But, I got a problem.
In this program, when i use 'eraser' tool, the background image is erased too!
Actually, I just want to erase what i painted, except background image.
And then, I'd like to save only the painted ones(layer) as an image.
In this case, What should i do?
import sys
from PyQt5.QtCore import *
from PyQt5.QtCore import Qt
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtWidgets import (QApplication, QCheckBox, QGridLayout, QGroupBox,
QPushButton, QVBoxLayout, QWidget, QSlider)
QApplication.setAttribute(Qt.AA_EnableHighDpiScaling, True)
class CWidget(QWidget):
def __init__(self):
super().__init__()
# 전체 폼 박스
formbox = QHBoxLayout()
self.setLayout(formbox)
# 좌, 우 레이아웃박스
left = QVBoxLayout()
right = QVBoxLayout()
# 그룹박스2
gb = QGroupBox('펜 설정')
left.addWidget(gb)
grid = QGridLayout()
gb.setLayout(grid)
label = QLabel('펜 색상')
grid.addWidget(label, 1, 0)
self.pencolor = QColor(0, 0, 0)
self.penbtn = QPushButton()
self.penbtn.setStyleSheet('background-color: rgb(0,0,0)')
self.penbtn.clicked.connect(self.showColorDlg)
grid.addWidget(self.penbtn, 1, 1)
label = QLabel('펜 굵기')
grid.addWidget(label, 2, 0)
self.slider = QSlider(Qt.Horizontal)
self.slider.setMinimum(3)
self.slider.setMaximum(21)
self.slider.setValue(5)
self.slider.setFocusPolicy(Qt.StrongFocus)
self.slider.setTickPosition(QSlider.TicksBothSides)
self.slider.setTickInterval(1)
self.slider.setSingleStep(1)
grid.addWidget(self.slider)
# 그룹박스4
gb = QGroupBox('Eraser')
left.addWidget(gb)
hbox = QHBoxLayout()
gb.setLayout(hbox)
self.checkbox = QCheckBox('Eraser')
self.checkbox.stateChanged.connect(self.checkClicked)
hbox.addWidget(self.checkbox)
left.addStretch(1)
self.view = CView(self)
right.addWidget(self.view)
formbox.addLayout(left)
formbox.addLayout(right)
formbox.setStretchFactor(left, 0)
formbox.setStretchFactor(right, 1)
self.setGeometry(100, 100, 800, 500)
def checkClicked(self, state):
pass
def createExampleGroup(self):
groupBox = QGroupBox("Slider Example")
slider = QSlider(Qt.Horizontal)
slider.setFocusPolicy(Qt.StrongFocus)
slider.setTickPosition(QSlider.TicksBothSides)
slider.setTickInterval(10)
slider.setSingleStep(1)
vbox = QVBoxLayout()
vbox.addWidget(slider)
vbox.addStretch(1)
groupBox.setLayout(vbox)
return groupBox
def showColorDlg(self):
color = QColorDialog.getColor()
sender = self.sender()
self.pencolor = color
self.penbtn.setStyleSheet('background-color: {}'.format(color.name()))
# QGraphicsView display QGraphicsScene
class CView(QGraphicsView):
def __init__(self, parent):
super().__init__(parent)
self.scene = QGraphicsScene()
self.setScene(self.scene)
self.items = []
self.start = QPointF()
self.end = QPointF()
self.backgroundImage = None
self.graphicsPixmapItem = None
self.setRenderHint(QPainter.HighQualityAntialiasing)
self.open()
def moveEvent(self, e):
rect = QRectF(self.rect())
rect.adjust(0, 0, -2, -2)
self.scene.setSceneRect(rect)
def mousePressEvent(self, e):
if e.button() == Qt.LeftButton:
# 시작점 저장
self.start = e.pos()
self.end = e.pos()
def mouseMoveEvent(self, e):
# e.buttons()는 정수형 값을 리턴, e.button()은 move시 Qt.Nobutton 리턴
if e.buttons() & Qt.LeftButton:
self.end = e.pos()
if self.parent().checkbox.isChecked():
pen = QPen(QColor(255, 255, 255), 10)
path = QPainterPath()
path.moveTo(self.start)
path.lineTo(self.end)
self.scene.addPath(path, pen)
self.start = e.pos()
return None
pen = QPen(self.parent().pencolor, self.parent().slider.value())
# Path 이용
path = QPainterPath()
path.moveTo(self.start)
path.lineTo(self.end)
self.scene.addPath(path, pen)
# 시작점을 다시 기존 끝점으로
self.start = e.pos()
def stretch(self, state):
self._set_image(state == 2)
def open(self):
fileName, _ = QFileDialog.getOpenFileName(self, "Open File", QDir.currentPath(), filter='Images (*.png *.xpm *.jpg *jpeg)')
if fileName:
image = QImage(fileName)
if image.isNull():
QMessageBox.information(self, "Image Viewer",
"Cannot load %s." % fileName)
return
self.backgroundImage = fileName
self._set_image(False)
def _set_image(self, stretch: bool):
tempImg = QPixmap(self.backgroundImage)
if stretch:
tempImg = tempImg.scaled(self.scene.width(), self.scene.height())
if self.graphicsPixmapItem is not None:
self.scene.removeItem(self.graphicsPixmapItem)
self.graphicsPixmapItem = QGraphicsPixmapItem(tempImg)
self.scene.addItem(self.graphicsPixmapItem)
if __name__ == '__main__':
app = QApplication(sys.argv)
w = CWidget()
w.show()
sys.exit(app.exec_())
You can create another transparent item where you draw and that is on the QGraphicsPixmapItem. For painting it is only necessary to draw on a transparent QPixmap that is in the transparent item, and for the deletion we use the composition mode QPainter::CompositionMode_Clear as I indicate in this answer.
Considering the above the solution is:
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
class LayerItem(QtWidgets.QGraphicsRectItem):
DrawState, EraseState = range(2)
def __init__(self, parent=None):
super().__init__(parent)
self.current_state = LayerItem.DrawState
self.setPen(QtGui.QPen(QtCore.Qt.NoPen))
self.m_line_eraser = QtCore.QLineF()
self.m_line_draw = QtCore.QLineF()
self.m_pixmap = QtGui.QPixmap()
def reset(self):
r = self.parentItem().pixmap().rect()
self.setRect(QtCore.QRectF(r))
self.m_pixmap = QtGui.QPixmap(r.size())
self.m_pixmap.fill(QtCore.Qt.transparent)
def paint(self, painter, option, widget=None):
super().paint(painter, option, widget)
painter.save()
painter.drawPixmap(QtCore.QPoint(), self.m_pixmap)
painter.restore()
def mousePressEvent(self, event):
if self.current_state == LayerItem.EraseState:
self._clear(event.pos().toPoint())
elif self.current_state == LayerItem.DrawState:
self.m_line_draw.setP1(event.pos())
self.m_line_draw.setP2(event.pos())
super().mousePressEvent(event)
event.accept()
def mouseMoveEvent(self, event):
if self.current_state == LayerItem.EraseState:
self._clear(event.pos().toPoint())
elif self.current_state == LayerItem.DrawState:
self.m_line_draw.setP2(event.pos())
self._draw_line(
self.m_line_draw, QtGui.QPen(self.pen_color, self.pen_thickness)
)
self.m_line_draw.setP1(event.pos())
super().mouseMoveEvent(event)
def _draw_line(self, line, pen):
painter = QtGui.QPainter(self.m_pixmap)
painter.setPen(pen)
painter.drawLine(line)
painter.end()
self.update()
def _clear(self, pos):
painter = QtGui.QPainter(self.m_pixmap)
r = QtCore.QRect(QtCore.QPoint(), 10 * QtCore.QSize())
r.moveCenter(pos)
painter.setCompositionMode(QtGui.QPainter.CompositionMode_Clear)
painter.eraseRect(r)
painter.end()
self.update()
#property
def pen_thickness(self):
return self._pen_thickness
#pen_thickness.setter
def pen_thickness(self, thickness):
self._pen_thickness = thickness
#property
def pen_color(self):
return self._pen_color
#pen_color.setter
def pen_color(self, color):
self._pen_color = color
#property
def current_state(self):
return self._current_state
#current_state.setter
def current_state(self, state):
self._current_state = state
class GraphicsView(QtWidgets.QGraphicsView):
def __init__(self, parent=None):
super().__init__(parent)
self.setScene(QtWidgets.QGraphicsScene(self))
self.setRenderHint(QtGui.QPainter.HighQualityAntialiasing)
self.setAlignment(QtCore.Qt.AlignCenter)
self.background_item = QtWidgets.QGraphicsPixmapItem()
self.foreground_item = LayerItem(self.background_item)
self.scene().addItem(self.background_item)
def set_image(self, image):
self.scene().setSceneRect(
QtCore.QRectF(QtCore.QPointF(), QtCore.QSizeF(image.size()))
)
self.background_item.setPixmap(image)
self.foreground_item.reset()
self.fitInView(self.background_item, QtCore.Qt.KeepAspectRatio)
self.centerOn(self.background_item)
class MainWindow(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super().__init__(parent)
menu = self.menuBar().addMenu(self.tr("File"))
open_action = menu.addAction(self.tr("Open image..."))
open_action.triggered.connect(self.open_image)
pen_group = QtWidgets.QGroupBox(self.tr("Pen settings"))
eraser_group = QtWidgets.QGroupBox(self.tr("Eraser"))
self.pen_button = QtWidgets.QPushButton(clicked=self.showColorDlg)
color = QtGui.QColor(0, 0, 0)
self.pen_button.setStyleSheet(
"background-color: {}".format(color.name())
)
self.pen_slider = QtWidgets.QSlider(
QtCore.Qt.Horizontal,
minimum=3,
maximum=21,
value=5,
focusPolicy=QtCore.Qt.StrongFocus,
tickPosition=QtWidgets.QSlider.TicksBothSides,
tickInterval=1,
singleStep=1,
valueChanged=self.onThicknessChanged,
)
self.eraser_checkbox = QtWidgets.QCheckBox(
self.tr("Eraser"), stateChanged=self.onStateChanged
)
self.view = GraphicsView()
self.view.foreground_item.pen_thickness = self.pen_slider.value()
self.view.foreground_item.pen_color = color
# layouts
pen_lay = QtWidgets.QFormLayout(pen_group)
pen_lay.addRow(self.tr("Pen color"), self.pen_button)
pen_lay.addRow(self.tr("Pen thickness"), self.pen_slider)
eraser_lay = QtWidgets.QVBoxLayout(eraser_group)
eraser_lay.addWidget(self.eraser_checkbox)
vlay = QtWidgets.QVBoxLayout()
vlay.addWidget(pen_group)
vlay.addWidget(eraser_group)
vlay.addStretch()
central_widget = QtWidgets.QWidget()
self.setCentralWidget(central_widget)
lay = QtWidgets.QHBoxLayout(central_widget)
lay.addLayout(vlay, stretch=0)
lay.addWidget(self.view, stretch=1)
self.resize(640, 480)
#QtCore.pyqtSlot(int)
def onStateChanged(self, state):
self.view.foreground_item.current_state = (
LayerItem.EraseState
if state == QtCore.Qt.Checked
else LayerItem.DrawState
)
#QtCore.pyqtSlot(int)
def onThicknessChanged(self, value):
self.view.foreground_item.pen_thickness = value
#QtCore.pyqtSlot()
def showColorDlg(self):
color = QtWidgets.QColorDialog.getColor(
self.view.foreground_item.pen_color, self
)
self.view.foreground_item.pen_color = color
self.pen_button.setStyleSheet(
"background-color: {}".format(color.name())
)
def open_image(self):
filename, _ = QtWidgets.QFileDialog.getOpenFileName(
self,
"Open File",
QtCore.QDir.currentPath(),
filter="Images (*.png *.xpm *.jpg *jpeg)",
)
if filename:
pixmap = QtGui.QPixmap(filename)
if pixmap.isNull():
QtWidgets.QMessageBox.information(
self, "Image Viewer", "Cannot load %s." % filename
)
return
self.view.set_image(pixmap)
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
w = MainWindow()
w.show()
sys.exit(app.exec_())
I want to update the opacity of some QGraphicsItem after the mouse clicking. As suggested from other solution, the QGraphicScene manually update the GraphicsItem after the mouser press event. I have tried different setOpacity() and update() in QGraphicsScene and QGraphicsItem. But none works and do not know what is wrong.
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
CUBE_POS = {
"a":( 8.281, 18.890),
"b":( 8.668, 23.692),
"c":( 21.493, 23.423),
"d":( 21.24, 15.955),
}
class CubeItem(QGraphicsItem):
def __init__(self, x, y, parent=None):
super(CubeItem,self).__init__(parent)
self.x = x
self.y = y
self.polygon = QPolygonF([
QPointF(self.x-10, self.y-10), QPointF(self.x-10, self.y+10),
QPointF(self.x+10, self.y+10), QPointF(self.x+10, self.y-10),
])
self._painter = QPainter()
##Estimate the drawing area
def boundingRect(self):
return QRectF(self.x-10, self.y-10, 20, 20)
##Real Shape of drawing area
def shape(self):
path = QPainterPath()
path.addRect(self.x-10, self.y-10, 20, 20)
return path
##paint function called by graphicview
def paint(self, painter, option, widget):
painter.setBrush(Qt.red)
painter.setOpacity(0.2)
painter.drawRect(self.x-10, self.y-10, 20, 20)
self._painter = painter
def activate(self):
try:
#self._painter.setOpacity(1.0)
self.setOpacity(1.0)
self.update()
except ValueError as e:
print(e)
class TagScene(QGraphicsScene):
def __init__(self, parent=None):
super(TagScene, self).__init__(parent)
self.cubes_items_ref = {}
self.addCubes()
def addCubes(self):
for cube in CUBE_POS:
newCube = CubeItem(CUBE_POS[cube][0]*15,
CUBE_POS[cube][1]*15)
self.addItem(newCube)
self.cubes_items_ref[cube] = newCube
def mousePressEvent(self, event):
print("mouse pressed")
#for cube in self.cubes_items_ref:
# self.cubes_items_ref[cube].setOpacity(1.0)
# #self.cubes_items_ref[cube].activate()
#self.update(QRectF(0,0,500,500))
for cube in self.items():
cube.setOpacity(1.0)
self.update(QRectF(0,0,500,500))
class MainWindow(QMainWindow):
def __init__(self):
super(MainWindow, self).__init__()
layout = QHBoxLayout()
self.scene = TagScene()
self.view = QGraphicsView(self.scene)
self.scene.setSceneRect(QRectF(0,0,500,500))
layout.addWidget(self.view)
self.widget = QWidget()
self.widget.setLayout(layout)
self.setCentralWidget(self.widget)
if __name__ == "__main__":
app = QApplication(sys.argv)
test = MainWindow()
test.show()
sys.exit(app.exec_())
The problem is that when you overwrite the paint method of the QGraphicsItem you are setting a constant opacity
def paint(self, painter, option, widget):
painter.setBrush(Qt.red)
painter.setOpacity(0.2) # <-- this line is the problem
painter.drawRect(self.x-10, self.y-10, 20, 20)
self._painter = painter
And you will not use the opacity that the QPainter already passes paint() method.
If you want to set an initial opacity you must do it in the constructor.On the other hand the setOpacity() method already calls update() so it is not necessary to make an explicit call.
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
CUBE_POS = {
"a": (8.281, 18.890),
"b": (8.668, 23.692),
"c": (21.493, 23.423),
"d": (21.24, 15.955),
}
class CubeItem(QtWidgets.QGraphicsItem):
def __init__(self, x, y, parent=None):
super(CubeItem, self).__init__(parent)
self.x = x
self.y = y
self.polygon = QtGui.QPolygonF(
[
QtCore.QPointF(self.x - 10, self.y - 10),
QtCore.QPointF(self.x - 10, self.y + 10),
QtCore.QPointF(self.x + 10, self.y + 10),
QtCore.QPointF(self.x + 10, self.y - 10),
]
)
self.setOpacity(0.2) # initial opacity
##Estimate the drawing area
def boundingRect(self):
return QtCore.QRectF(self.x - 10, self.y - 10, 20, 20)
##Real Shape of drawing area
def shape(self):
path = QtGui.QPainterPath()
path.addRect(self.boundingRect())
return path
##paint function called by graphicview
def paint(self, painter, option, widget):
painter.setBrush(QtCore.Qt.red)
painter.drawRect(self.x - 10, self.y - 10, 20, 20)
class TagScene(QtWidgets.QGraphicsScene):
def __init__(self, parent=None):
super(TagScene, self).__init__(parent)
self.cubes_items_ref = {}
self.addCubes()
def addCubes(self):
for cube in CUBE_POS:
newCube = CubeItem(CUBE_POS[cube][0] * 15, CUBE_POS[cube][1] * 15)
self.addItem(newCube)
self.cubes_items_ref[cube] = newCube
def mousePressEvent(self, event):
for cube in self.items():
cube.setOpacity(1.0) # update opacity
class MainWindow(QtWidgets.QMainWindow):
def __init__(self):
super(MainWindow, self).__init__()
layout = QtWidgets.QHBoxLayout()
self.scene = TagScene()
self.view = QtWidgets.QGraphicsView(self.scene)
self.scene.setSceneRect(QtCore.QRectF(0, 0, 500, 500))
layout.addWidget(self.view)
self.widget = QtWidgets.QWidget()
self.widget.setLayout(layout)
self.setCentralWidget(self.widget)
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
test = MainWindow()
test.show()
sys.exit(app.exec_())
I'm trying to paint some ticks in my custom progressbar but I'm not clear on why the line isn't showing up at all?
import sys
import os
sys.path.append('Z:\\pipeline\\site-packages')
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
from PySide import QtGui, QtCore
class QProgressBarPro(QtGui.QProgressBar):
progressClicked = QtCore.Signal()
progressChanging = QtCore.Signal()
progressChanged = QtCore.Signal()
def __init__(self, parent=None):
super(QProgressBarPro, self).__init__(parent)
self.default_value = 50.0
self.lmb_pressed = False
self.setFormat('%p')
self.setRange(0.0, 100.0)
self.stepEnabled = True
self.step = 5
self.setToolTip('<strong>Press+Hold+Ctrl</strong> for percise values<br><strong>Right-Click</strong> to reset default value')
def step_round(self, x, base=5):
return int(base * round(float(x)/base))
def set_value_from_cursor(self, xpos):
width = self.frameGeometry().width()
percent = float(xpos) / width
val = self.maximum() * percent
if self.stepEnabled:
modifiers = QtGui.QApplication.keyboardModifiers()
if modifiers != QtCore.Qt.ControlModifier:
val = self.step_round(val, self.step)
self.setValue(val)
def mousePressEvent(self, event):
self.progressClicked.emit()
mouse_button = event.button()
if mouse_button == QtCore.Qt.RightButton:
self.setValue(self.default_value)
else:
xpos = event.pos().x()
self.set_value_from_cursor(xpos)
self.lmb_pressed = True
self.progressChanging.emit()
def mouseReleaseEvent(self, event):
self.lmb_pressed = False
self.progressChanged.emit()
def mouseMoveEvent(self, event):
if self.lmb_pressed:
xpos = event.pos().x()
self.set_value_from_cursor(xpos)
self.progressChanging.emit()
def paintEvent(self, event):
painter = QtGui.QPainter()
painter.drawLine(10, 0, 10, 10)
QtGui.QProgressBar.paintEvent(self, event)
# DEMO
class Example(QtGui.QWidget):
def __init__(self):
super(Example, self).__init__()
self.initUI()
def initUI(self):
self.ui_progress = QProgressBarPro()
self.ui_progress.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
self.ui_progress.setValue(10)
gdl = QtGui.QVBoxLayout()
gdl.addWidget(self.ui_progress)
self.setLayout(gdl)
self.resize(300, 300)
self.setWindowTitle('Tooltips')
self.show()
def main():
app = QtGui.QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
You need to change your paintEvent function.
I wrote a first approach that provides same result as in your image:
def paintEvent(self, event):
QtGui.QProgressBar.paintEvent(self, event)
painter = QtGui.QPainter(self)
brush = QtGui.QBrush(QtCore.Qt.SolidPattern)
# Set gray color
brush.setColor(QtGui.QColor(204,204,204))
painter.setPen(QtGui.QPen(brush, 2, QtCore.Qt.SolidLine,QtCore.Qt.RoundCap))
#print(str(self.width())+","+str(self.height()))
progressbarwidth = self.width()
progressbarheight = self.height()
## Drawing one vertical line each 1/5
painter.drawLine(progressbarwidth*1/5, 0, progressbarwidth*1/5, progressbarheight)
painter.drawLine(progressbarwidth*2/5, 0, progressbarwidth*2/5, progressbarheight)
painter.drawLine(progressbarwidth*3/5, 0, progressbarwidth*3/5, progressbarheight)
painter.drawLine(progressbarwidth*4/5, 0, progressbarwidth*4/5, progressbarheight)
The achieved outcome is shown here.