PYQT how to draw line between two buttons - python-3.x

from PyQt4 import QtGui, QtCore
class Window(QtGui.QWidget):
def __init__(self):
QtGui.QWidget.__init__(self)
self.view = View(self)
self.button = QtGui.QPushButton('Clear View', self)
self.button.clicked.connect(self.handleClearView)
layout = QtGui.QVBoxLayout(self)
layout.addWidget(self.view)
layout.addWidget(self.button)
def handleClearView(self):
self.view.scene().clear()
class DragButton(QtGui.QPushButton):
def mousePressEvent(self, event):
self.__mousePressPos = None
self.__mouseMovePos = None
if event.button() == QtCore.Qt.LeftButton:
self.__mousePressPos = event.globalPos()
self.__mouseMovePos = event.globalPos()
#super(DragButton, self).mousePressEvent(event)
def mouseMoveEvent(self, event):
if event.buttons() == QtCore.Qt.LeftButton:
# adjust offset from clicked point to origin of widget
currPos = self.mapToGlobal(self.pos())
globalPos = event.globalPos()
diff = globalPos - self.__mouseMovePos
newPos = self.mapFromGlobal(currPos + diff)
self.move(newPos)
self.__mouseMovePos = globalPos
#super(DragButton, self).mouseMoveEvent(event)
def mouseReleaseEvent(self, event):
if self.__mousePressPos is not None:
moved = event.globalPos() - self.__mousePressPos
if moved.manhattanLength() > 3:
event.ignore()
return
#super(DragButton, self).mouseReleaseEvent(event)
class View(QtGui.QGraphicsView):
def __init__(self, parent):
QtGui.QGraphicsView.__init__(self, parent)
self.setScene(QtGui.QGraphicsScene(self))
self.setSceneRect(QtCore.QRectF(self.viewport().rect()))
btn1=DragButton('Test1', self)
btn2=DragButton('Test2', self)
def mousePressEvent(self, event):
self._start = event.pos()
def mouseReleaseEvent(self, event):
start = QtCore.QPointF(self.mapToScene(self._start))
end = QtCore.QPointF(self.mapToScene(event.pos()))
self.scene().addItem(
QtGui.QGraphicsLineItem(QtCore.QLineF(start, end)))
for point in (start, end):
text = self.scene().addSimpleText(
'(%d, %d)' % (point.x(), point.y()))
text.setBrush(QtCore.Qt.red)
text.setPos(point)
if __name__ == '__main__':
import sys
app = QtGui.QApplication(sys.argv)
window = Window()
window.resize(640, 480)
window.show()
sys.exit(app.exec_())
Here is my code. There are two movable buttons on the QGraphicsView and I can draw line on the QGraphicsView with mouse dragging. But what I want to do is to draw line between two buttons. For detail, If I right click the btn1(Test1) and then right click the btn2(Test2) , the line would be created between two buttons. I'm struggling this problem for a month. Plz Help!

I am assuming that the line you need to draw between the buttons must also be movable. If not it is just simple you can just use :
lines = QtGui.QPainter()
lines.setPen(self)
lines.drawLine(x1,y1,x2,y2)
So, if the line needs to be movable along with the buttons then first you create a mini widget consisting of Two Buttons and the Line, so you can move the whole widget. This might help!, in that case.

Related

PySide2: "MouseReleaseEvernt" not triggered in QGraphicsItem

I have a custom QGraphicsItem on a QgraphicsScene. And I'm trying to draw on QGraphicsItem following mouse events. Here is what I implemented:
The custom QGraphicsItem in implemented in GraphicsItem_custom.py
from PySide2.QtWidgets import QGraphicsItem
from PySide2.QtCore import QPointF, QRectF, Qt, QRect, QPoint
from PySide2.QtGui import QPen, QPainter, QPixmap
class GraphicsItem_custom(QGraphicsItem):
def __init__(self,*args, **kwargs):
super().__init__(*args, **kwargs)
self.start, self.end = QPoint(), QPoint()
self.rectangles = []
def boundingRect(self):
return QRectF(0, 0, 500, 300)
def paint(self, painter, option, widget):
painter.setPen(QPen(Qt.red, 6, Qt.SolidLine))
painter.drawText(QPointF(0, 10), "Hiya")
painter.drawRect(self.boundingRect())
for rectangle in self.rectangles:
painter.drawRect(rectangle)
if not self.start.isNull() and not self.end.isNull() and self.start != self.end:
rect = QRect(self.start, self.end)
print("paintEvent start: " + str(self.start) + ", end: " + str(self.end))
print("")
painter.drawRect(rect.normalized())
def mousePressEvent(self, event):
super().mousePressEvent(event)
print("Pressed")
if event.buttons() and Qt.LeftButton:
self.start = event.pos()
self.end = self.start
self.update()
print("left button")
def mouseMoveEvent(self, event):
print("Move")
super().mouseMoveEvent(event)
if event.buttons() and Qt.LeftButton:
self.end = event.pos()
self.update()
def mouseReleaseEvent(self, event):
super().mouseReleaseEvent(event)
print("Released")
if event.button() and Qt.LeftButton:
if self.start != self.end:
r = QRect(self.start, self.end).normalized()
self.rectangles.append(r)
self.start = self.end = QPoint()
self.update()
Then, in main.py I create the scene and view, and add the item onto the scene:
class MyApp(QMainWindow):
def __init__(self):
super().__init__()
self.window_width, self.window_height = 1200, 800
self.setMinimumSize(self.window_width, self.window_height)
self.scene = QGraphicsScene(self)
self.view = QGraphicsView(self.scene, self)
self.view.setGeometry(0,0,1000, 700)
self.item = GraphicsItem_custom()
self.scene.addItem(self.item)
if __name__ == '__main__':
# don't auto scale when drag app to a different monitor.
# QApplication.setAttribute(Qt.HighDpiScaleFactorRoundingPolicy.PassThrough)
app = QApplication(sys.argv)
app.setStyleSheet('''
QWidget {
font-size: 30px;
}
''')
myApp = MyApp()
myApp.show()
try:
sys.exit(app.exec_())
except SystemExit:
print('Closing Window...')
When I run this code, the mousePressEvent() is triggered when I press, however, mouseReleaseEvent() is not when triggered when I release. Can anyone tell me what I did wrong?
The documentation of mousePressEvent() explains:
If you do reimplement this function, event will by default be accepted (see QEvent::accept()), and this item is then the mouse grabber. This allows the item to receive future move, release and doubleclick events.
If you call the base implementation like this:
super().mousePressEvent(event)
the result will the same as not reimplementing the function (you're calling the default behavior), so the event will not accepted, meaning that the item will not receive move, release and doubleclick events, unless you've set specific flags that trigger those event handlers due to their nature (like Qt.ItemIsMovable).
You have to carefully decide if you actually need to call the base implementation or not (usually depending on the flags), and eventually add this at some point in the mousePressEvent() override:
event.setAccepted(True)

How to make a layout with only aboslute positioning in pyqt

I want to make a layout where the user is able to move the widget inside freely with no constraints of rows or column. So I'm using absolute positioning. I'm able to make it happen in a window with no layout but I don't know what to use as a layout , problem is in the commented line in the code.
from PyQt5.QtWidgets import QWidget, QLabel, QApplication,QVBoxLayout,QHBoxLayout
from PyQt5.QtCore import Qt, QMimeData
from PyQt5.QtGui import QDrag
class DragLabel(QLabel):
def mouseMoveEvent(self, e):
if e.buttons() == Qt.LeftButton:
drag = QDrag(self)
mime = QMimeData()
drag.setMimeData(mime)
drag.exec_(Qt.MoveAction)
class Window(QWidget):
def __init__(self):
super().__init__()
self.setAcceptDrops(True)
self.label = DragLabel('first', self)
self.label2 = DragLabel('second', self)
self.label3 = DragLabel('third', self)
self.label.move(50, 50)
self.label2.move(100, 100)
self.label3.move(150, 150)
# self.main_frame=QHBoxLayout()
# self.classic_frame=QVBoxLayout()
#what should I use here to make a frame working with absolute position only
# self.absolute_frame = ???
# self.absolute_frame.addWidget(self.label)
# self.absolute_frame.addWidget(self.label2)
# self.absolute_frame.addWidget(self.label3)
# self.main_frame.addLayout(self.classic_frame)
# self.main_frame.addLayout(self.absolute_frame)
# self.setLayout(self.main_frame)
def dragEnterEvent(self, e):
widget = e.source()
if isinstance(widget,DragLabel):
e.accept()
def dropEvent(self, e):
pos = e.pos()
widget_dep = e.source()
if isinstance(widget_dep,DragLabel):
widget_dep_name = widget_dep.text()
print(widget_dep_name)
widget_dep.move(pos.x(),pos.y())
if __name__ == '__main__':
app = QApplication([])
w = Window()
w.show()
app.exec_()

How can I delete this QGraphicsLineItem when context menu is open in a QGraphicsPixmapItem?

I'm developing a GUI where you can connect nodes between them except in a few special cases. This implementation works perfectly fine most of the time, but after some testing i found that, when I connect one QGraphicsPixmapItem with another through a QGraphicsLineItem, and the user opens the contextual menu before completing the link, the line get stuck, and it cannot be deleted.
The process to link two elements is to first press the element, then keep pressing while moving the line and releasing when the pointer is over the other element. This is achieved using mousePressEvent, mouseMoveEvent and mouseReleaseEvent, respectively.
This code is an example:
#!/usr/bin/env python3
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
import sys
class Ellipse(QGraphicsEllipseItem):
def __init__(self, x, y):
super(Ellipse, self).__init__(x, y, 30, 30)
self.setBrush(QBrush(Qt.darkBlue))
self.setFlag(QGraphicsItem.ItemIsMovable)
self.setZValue(100)
def contextMenuEvent(self, event):
menu = QMenu()
first_action = QAction("First action")
second_action = QAction("Second action")
menu.addAction(first_action)
menu.addAction(second_action)
action = menu.exec(event.screenPos())
class Link(QGraphicsLineItem):
def __init__(self, x, y):
super(Link, self).__init__(x, y, x, y)
self.pen_ = QPen()
self.pen_.setWidth(2)
self.pen_.setColor(Qt.red)
self.setPen(self.pen_)
def updateEndPoint(self, x2, y2):
line = self.line()
self.setLine(line.x1(), line.y1(), x2, y2)
class Scene(QGraphicsScene):
def __init__(self):
super(Scene, self).__init__()
self.link = None
self.link_original_node = None
self.addItem(Ellipse(200, 400))
self.addItem(Ellipse(400, 400))
def mousePressEvent(self, event):
if event.button() == Qt.LeftButton:
item = self.itemAt(event.scenePos(), QTransform())
if item is not None:
self.link_original_node = item
offset = item.boundingRect().center()
self.link = Link(item.scenePos().x() + offset.x(), item.scenePos().y() + offset.y())
self.addItem(self.link)
def mouseMoveEvent(self, event):
super().mouseMoveEvent(event)
if self.link is not None:
self.link.updateEndPoint(event.scenePos().x(), event.scenePos().y())
def mouseReleaseEvent(self, event):
super().mouseReleaseEvent(event)
if self.link is not None:
item = self.itemAt(event.scenePos(), QTransform())
if isinstance(item, (Ellipse, Link)):
self.removeItem(self.link)
self.link_original_node = None
self.link = None
class MainWindow(QMainWindow):
def __init__(self):
super(QMainWindow, self).__init__()
self.scene = Scene()
self.canvas = QGraphicsView()
self.canvas.setScene(self.scene)
self.setCentralWidget(self.canvas)
self.setGeometry(500, 200, 1000, 600)
self.setContextMenuPolicy(Qt.NoContextMenu)
app = QApplication(sys.argv)
win = MainWindow()
win.show()
sys.exit(app.exec())
How can I get rid off the line before/after the context menu event? I tried to stop them, but I do not know how.
Assuming that the menu is only triggered from a mouse button press, the solution is to remove any existing link item in the mouseButtonPress too.
def mousePressEvent(self, event):
if self.link is not None:
self.removeItem(self.link)
self.link_original_node = None
self.link = None
# ...
Note that itemAt for very small items is not always reliable, as the item's shape() might be slightly off the mapped mouse position. Since the link would be removed in any case, just do the same in the mouseReleaseEvent():
def mouseReleaseEvent(self, event):
super().mouseReleaseEvent(event)
if self.link is not None:
item = self.itemAt(event.scenePos(), QTransform())
if isinstance(item, Ellipse):
# do what you need with the linked ellipses
# note the indentation level
self.removeItem(self.link)
self.link_original_node = None
self.link = None

pyqt scrollarea not resized after dragndrop

short version:
- take the code, run it, (all you need is two png icons)
- resize the window to be a lot larger
- dragndrop one of the icon far away (at least 300+ pixels away)
- then resize window back to original size
- then try to scroll to see the icon you dragndropped away.
- you will not be able. because scrollarea is too small.
- why?
long version:
i'm having trouble figuring how to update my scrollarea to reflect added or modified contents in my application.
i'm displaying icons, i can dragndrop them.
if i make the window bigger, dragndrop one icon to the bottom,
and then size back my window,
the scrollarea does not allow me to scroll to the bottom to see my icon.
basicaly, once the app started, scrollarea dimension never change.
how can i make the scrollarea, upon dragndrop, to update to new size ?
it could be bigger like shown in the screenshot below,
or smaller if all my icons are grouped in upper left corner for example..
if the content fit in the window, i will not show the slider.
here's a screenshot showing the problem,
it's the same window, i just resize it, and dragndrop one icon at the bottom:
(scrollarea is not updated, so i cannot scroll down to my icon i've put at the bottom)
here's the code so far:
#!/usr/bin/python3
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
import sys
class DragWidget(QFrame):
def __init__(self, parent=None):
super(DragWidget, self).__init__(parent)
self.setMinimumSize(200, 200)
self.setAcceptDrops(True)
test_icon1 = QLabel(self)
test_icon1.setPixmap(QPixmap('./images/closeicon.png'))
test_icon1.move(20, 20)
test_icon1.show()
test_icon1.setAttribute(Qt.WA_DeleteOnClose)
test_icon2 = QLabel(self)
test_icon2.setPixmap(QPixmap('./images/openicon.png'))
test_icon2.move(60, 20)
test_icon2.show()
test_icon2.setAttribute(Qt.WA_DeleteOnClose)
def dragEnterEvent(self, event):
if event.mimeData().hasFormat('application/x-dnditemdata'):
if event.source() == self:
event.setDropAction(Qt.MoveAction)
event.accept()
else:
event.acceptProposedAction()
else:
event.ignore()
dragMoveEvent = dragEnterEvent
def dropEvent(self, event):
if event.mimeData().hasFormat('application/x-dnditemdata'):
itemData = event.mimeData().data('application/x-dnditemdata')
dataStream = QDataStream(itemData, QIODevice.ReadOnly)
pixmap = QPixmap()
offset = QPoint()
dataStream >> pixmap >> offset
newIcon = QLabel(self)
newIcon.setPixmap(pixmap)
newIcon.move(event.pos() - offset)
newIcon.show()
newIcon.setAttribute(Qt.WA_DeleteOnClose)
if event.source() == self:
event.setDropAction(Qt.MoveAction)
event.accept()
else:
event.acceptProposedAction()
else:
event.ignore()
def mousePressEvent(self, event):
child = self.childAt(event.pos())
if not child:
return
pixmap = QPixmap(child.pixmap())
itemData = QByteArray()
dataStream = QDataStream(itemData, QIODevice.WriteOnly)
dataStream << pixmap << QPoint(event.pos() - child.pos())
mimeData = QMimeData()
mimeData.setData('application/x-dnditemdata', itemData)
drag = QDrag(self)
drag.setMimeData(mimeData)
drag.setPixmap(pixmap)
drag.setHotSpot(event.pos() - child.pos())
tempPixmap = QPixmap(pixmap)
painter = QPainter()
painter.begin(tempPixmap)
painter.fillRect(pixmap.rect(), QColor(127, 127, 127, 127))
painter.end()
child.setPixmap(tempPixmap)
if drag.exec_(Qt.CopyAction | Qt.MoveAction) == Qt.MoveAction:
child.close()
else:
child.show()
child.setPixmap(pixmap)
class Window(QWidget):
def __init__(self, parent=None):
super(Window, self).__init__()
widget = QWidget()
palette = QPalette()
palette.setBrush(QPalette.Background, QBrush(QPixmap("images/pattern.png")))
widget.setPalette(palette)
layout = QVBoxLayout(self)
layout.addWidget(DragWidget())
widget.setLayout(layout)
scroll = QScrollArea()
scroll.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
scroll.setWidgetResizable(True)
scroll.setWidget(widget)
vlayout = QVBoxLayout(self)
vlayout.setContentsMargins(0, 0, 0, 0)
vlayout.setSpacing(0)
vlayout.addWidget(scroll)
self.setLayout(vlayout)
self.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
window = Window('./')
sys.exit(app.exec_())
it turned out, i needed to modify dropEvent method,
to take the X and Y of the dropped icon and use those values for setMinimumSize().
like this:
#!/usr/bin/python3
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
import sys
class DragWidget(QFrame):
def __init__(self, parent=None):
super(DragWidget, self).__init__(parent)
self.setMinimumSize(200, 200)
self.setAcceptDrops(True)
self.test_icon1 = QLabel(self)
self.test_icon1.setPixmap(QPixmap('./images/closeicon.png'))
self.test_icon1.move(20, 20)
self.test_icon1.show()
self.test_icon1.setAttribute(Qt.WA_DeleteOnClose)
self.test_icon2 = QLabel(self)
self.test_icon2.setPixmap(QPixmap('./images/openicon.png'))
self.test_icon2.move(60, 20)
self.test_icon2.show()
self.test_icon2.setAttribute(Qt.WA_DeleteOnClose)
def dragEnterEvent(self, event):
if event.mimeData().hasFormat('application/x-dnditemdata'):
if event.source() == self:
event.setDropAction(Qt.MoveAction)
event.accept()
else:
event.acceptProposedAction()
else:
event.ignore()
dragMoveEvent = dragEnterEvent
def dropEvent(self, event):
if event.mimeData().hasFormat('application/x-dnditemdata'):
itemData = event.mimeData().data('application/x-dnditemdata')
dataStream = QDataStream(itemData, QIODevice.ReadOnly)
pixmap = QPixmap()
offset = QPoint()
dataStream >> pixmap >> offset
newIcon = QLabel(self)
newIcon.setPixmap(pixmap)
newIcon.move(event.pos() - offset)
newIcon.show()
newIcon.setAttribute(Qt.WA_DeleteOnClose)
if newIcon.y()+32 > self.minimumHeight():
self.setMinimumHeight(newIcon.y()+32)
if newIcon.x()+32 > self.minimumWidth():
self.setMinimumWidth(newIcon.x()+32)
if event.source() == self:
event.setDropAction(Qt.MoveAction)
event.accept()
else:
event.acceptProposedAction()
else:
event.ignore()
def mousePressEvent(self, event):
child = self.childAt(event.pos())
if not child:
return
pixmap = QPixmap(child.pixmap())
itemData = QByteArray()
dataStream = QDataStream(itemData, QIODevice.WriteOnly)
dataStream << pixmap << QPoint(event.pos() - child.pos())
mimeData = QMimeData()
mimeData.setData('application/x-dnditemdata', itemData)
drag = QDrag(self)
drag.setMimeData(mimeData)
drag.setPixmap(pixmap)
drag.setHotSpot(event.pos() - child.pos())
tempPixmap = QPixmap(pixmap)
painter = QPainter()
painter.begin(tempPixmap)
painter.fillRect(pixmap.rect(), QColor(127, 127, 127, 127))
painter.end()
child.setPixmap(tempPixmap)
if drag.exec_(Qt.CopyAction | Qt.MoveAction) == Qt.MoveAction:
child.close()
else:
child.show()
child.setPixmap(pixmap)
class Window(QWidget):
def __init__(self, parent=None):
super(Window, self).__init__()
self.pattern = "images/pattern.png"
self.widget = QWidget()
self.palette = QPalette()
self.palette.setBrush(QPalette.Background, QBrush(QPixmap(self.pattern)))
self.widget.setPalette(self.palette)
layout = QVBoxLayout(self)
layout.addWidget(DragWidget())
self.widget.setLayout(layout)
scroll = QScrollArea()
scroll.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)
scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarAsNeeded)
scroll.setWidgetResizable(True)
scroll.setWidget(self.widget)
vlayout = QVBoxLayout(self)
vlayout.setContentsMargins(0, 0, 0, 0)
vlayout.setSpacing(0)
vlayout.addWidget(scroll)
self.setLayout(vlayout)
self.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
window = Window('./')
window2 = Window('./')
sys.exit(app.exec_())
note the dropEvent() method of DragWidget() class.
if newIcon.y()+32 > self.minimumHeight():
self.setMinimumHeight(newIcon.y()+32)
if newIcon.x()+32 > self.minimumWidth():
self.setMinimumWidth(newIcon.x()+32)
so if the icon new position is greater than
the minimumSize (minimumWidth and minimumHeight),
then add the offset to self.minimumSize
thanks to Avaris from #pyqt channel for the help :)

pyqt5: why the mimeData().text() returns nothing?

learning PyQt5 recently, I've tried to drag a QPushButton learning this tutorial Drag & drop a button widget, and made some improvements to place the button more accurate, so I add
mime = e.mimeData().text()
x, y = mime.split(',')
according to #Avaris for this question, but I found e.mimeData().text() returned nothing which supposed to be the coordinate of local position of the cursor with respect to the button, i tried to print(mime), and got a blank line with nothing, then i print(mime.split(',')) and got ['']。
here's the code:
import sys
from PyQt5.QtWidgets import QPushButton, QWidget, QApplication, QLabel
from PyQt5.QtCore import Qt, QMimeData
from PyQt5.QtGui import QDrag
from PyQt5 import QtCore
class Button(QPushButton):
def __init__(self, title, parent):
super().__init__(title, parent)
def mouseMoveEvent(self, e):
if e.buttons() != Qt.RightButton:
return
mimeData = QMimeData()
drag = QDrag(self)
drag.setMimeData(mimeData)
dropAction = drag.exec_(Qt.MoveAction)
def mousePressEvent(self, e):
QPushButton.mousePressEvent(self, e)
if e.button() == Qt.LeftButton:
print('press')
class Example(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.setAcceptDrops(True)
self.button = Button('Button', self)
self.button.move(100, 65)
self.setWindowTitle('Click or Move')
self.setGeometry(300, 300, 280, 150)
def dragEnterEvent(self, e):
e.accept()
def dropEvent(self, e):
position = e.pos()
mime = e.mimeData().text()
x, y = mime.split(',')
#print(mime.split(','))
self.button.move(position - QtCore.QPoint(int(x), int(y)))
e.setDropAction(Qt.MoveAction)
e.accept()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Example()
ex.show()
app.exec_()
In the answer of #Avaris, you will notice they set the mimedata with the button position in the mouseMoveEvent:
mimeData = QtCore.QMimeData()
# simple string with 'x,y'
mimeData.setText('%d,%d' % (e.x(), e.y()))
The mimedata does not contain anything by default. You have to set everything yourself! Have a look at the documentation for QMimeData to see what else you can do (other than setting arbitrary text)
Drag and Drop in Camera View
def dragEnterEvent(self, event): # Drag lines
mimeData = QtCore.QMimeData()
if mimeData.hasText:
event.accept()
else:
event.ignore()
def dropEvent(self, event): # Drop lines
mimeData = QtCore.QMimeData()
format = 'application/x-qabstractitemmodeldatalist'
data=event.mimeData().data(format) # Drag Drop get data's name
name_str = codecs.decode(data,'utf-8') # Convert byte to string
mimeData.setText(name_str)
# print(name_str[26:].replace('\x00','').strip("")) # remove white space
if mimeData.hasText:
print(name_str)
# write what you will do

Resources