I have a PicButton class based on QAbtractButton that has the normal, hover and pressed. However, when clicked the button only changed to the pixmap_pressed briefly and then switch back to standard.
How can I make it behaves like a toggle button so that the pressed pixmap will stay after pressed?
import numpy as np
import time, sys
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import QMainWindow
class PicButton(QAbstractButton):
def __init__(self, pixmap, pixmap_hover, pixmap_pressed, parent=None):
super(PicButton, self).__init__(parent)
self.pixmap = pixmap
self.pixmap_hover = pixmap_hover
self.pixmap_pressed = pixmap_pressed
self.pressed.connect(self.update)
# self.released.connect(self.update)
def paintEvent(self, event):
pix = self.pixmap_hover if self.underMouse() else self.pixmap
if self.isDown():
pix = self.pixmap_pressed
painter = QPainter(self)
painter.drawPixmap(event.rect(), pix)
def enterEvent(self, event):
self.update()
def leaveEvent(self, event):
self.update()
def sizeHint(self):
return self.pixmap.size()
class App(QMainWindow):
def __init__(self):
super().__init__()
self.left = 0
self.top = 0
self.width = 800
self.height = 800
self.initUI()
def initUI(self):
self.setGeometry(self.left, self.top, self.width, self.height)
self.recBtn = PicButton(QPixmap('./img/playrecstop/rec_512.png'),QPixmap('./img/playrecstop/recHL_512.png'),\
QPixmap('./img/playrecstop/recActive_512.png'))
self.recBtn.setText("rec")
self.recBtn.clicked.connect(self.controlButtons)
self.stopBtn = PicButton(QPixmap('./img/playrecstop/stop_512.png'), QPixmap('./img/playrecstop/stopHL_512.png'),\
QPixmap('./img/playrecstop/stopActive_512.png'))
self.stopBtn.setText("stop")
self.stopBtn.clicked.connect(self.controlButtons)
self.leftLayout = QHBoxLayout()
self.rightLayout = QHBoxLayout()
self.rightLayout.addWidget(self.recBtn)
self.rightLayout.addWidget(self.stopBtn)
self.mainLayout = QHBoxLayout()
self.mainLayout.addLayout(self.leftLayout)
self.mainLayout.addLayout(self.rightLayout)
self.setCentralWidget(QWidget(self))
self.centralWidget().setLayout(self.mainLayout)
self.show()
def controlButtons(self):
sender = self.sender()
if (sender.text() == 'stop'):
print ("Stop")
elif (sender.text() == 'rec'):
print ("REC...")
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = App()
sys.exit(app.exec_())
Thanks
QAbstractButton has a checkable property that allows you to implement the logic you want:
class PicButton(QAbstractButton):
def __init__(self, pixmap, pixmap_hover, pixmap_pressed, parent=None):
super(PicButton, self).__init__(parent)
self.pixmap = pixmap
self.pixmap_hover = pixmap_hover
self.pixmap_pressed = pixmap_pressed
self.setCheckable(True)
def paintEvent(self, event):
pix = self.pixmap_hover if self.underMouse() else self.pixmap
if self.isChecked():
pix = self.pixmap_pressed
painter = QPainter(self)
painter.drawPixmap(event.rect(), pix)
def enterEvent(self, event):
self.update()
def leaveEvent(self, event):
self.update()
def sizeHint(self):
return self.pixmap.size()
Related
My code is drawing lines on a QImage using mousePressEvent and mouseReleaseEvent. It works fine but I would like a dynamic preview line to appear when I'm drawing the said line (ie on MouseMoveEvent). Right now the line just appears when I release the left mouse button and I can't see what I'm drawing.
I want the preview of the line to appear and update as I move my mouse, and only "fixate" when I release the left mouse button. Exactly like the MS Paint Line tool : https://youtu.be/YIw9ybdoM6o?t=207
Here is my code (it is derived from the Scribble Example):
from PyQt5.QtCore import QPoint, QRect, QSize, Qt
from PyQt5.QtGui import QImage, QPainter, QPen, QColor, qRgb
from PyQt5.QtWidgets import QApplication, QWidget, QMainWindow
import sys
class DrawingArea(QWidget):
def __init__(self, parent=None):
super(DrawingArea, self).__init__(parent)
self.setAttribute(Qt.WA_StaticContents)
self.scribbling = False
self.myPenWidth = 1
self.myPenColor = QColor('#000000')
self.image = QImage()
self.startPoint = QPoint()
def mousePressEvent(self, event):
if event.button() == Qt.LeftButton:
self.startPoint = event.pos()
self.scribbling = True
def mouseReleaseEvent(self, event):
if event.button() == Qt.LeftButton and self.scribbling:
self.drawLineTo(event.pos())
self.scribbling = False
def paintEvent(self, event):
painter = QPainter(self)
dirtyRect = event.rect()
painter.drawImage(dirtyRect, self.image, dirtyRect)
def resizeEvent(self, event):
if self.width() > self.image.width() or self.height() > self.image.height():
newWidth = max(self.width() + 128, self.image.width())
newHeight = max(self.height() + 128, self.image.height())
self.resizeImage(self.image, QSize(newWidth, newHeight))
self.update()
super(DrawingArea, self).resizeEvent(event)
def drawLineTo(self, endPoint):
painter = QPainter(self.image)
painter.setPen(QPen(self.myPenColor, self.myPenWidth, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin))
painter.drawLine(self.startPoint, endPoint)
rad = self.myPenWidth / 2 + 2
self.update(QRect(self.startPoint, endPoint).normalized().adjusted(-rad, -rad, +rad, +rad))
def resizeImage(self, image, newSize):
if image.size() == newSize:
return
newImage = QImage(newSize, QImage.Format_RGB32)
newImage.fill(qRgb(255, 255, 255))
painter = QPainter(newImage)
painter.drawImage(QPoint(0, 0), image)
self.image = newImage
class MainWindow(QMainWindow):
def __init__(self, parent=None):
QMainWindow.__init__(self, parent)
self.setCentralWidget(DrawingArea())
self.show()
def main():
app = QApplication(sys.argv)
ex = MainWindow()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
I can't figure out how to show the preview of the line I'm drawing and I haven't found a suitable answer yet. How can I go about doing this ?
You can draw the lines just within the paintEvent() method instead than directly on the image, then paint on the image when the mouse is actually released.
class DrawingArea(QWidget):
def __init__(self, parent=None):
super(DrawingArea, self).__init__(parent)
self.setAttribute(Qt.WA_StaticContents)
self.scribbling = False
self.myPenWidth = 1
self.myPenColor = QColor('#000000')
self.image = QImage()
self.startPoint = self.endPoint = None
def mousePressEvent(self, event):
if event.button() == Qt.LeftButton:
self.startPoint = event.pos()
def mouseMoveEvent(self, event):
if self.startPoint:
self.endPoint = event.pos()
self.update()
def mouseReleaseEvent(self, event):
if self.startPoint and self.endPoint:
self.updateImage()
def paintEvent(self, event):
painter = QPainter(self)
dirtyRect = event.rect()
painter.drawImage(dirtyRect, self.image, dirtyRect)
if self.startPoint and self.endPoint:
painter.drawLine(self.startPoint, self.endPoint)
def updateImage(self):
if self.startPoint and self.endPoint:
painter = QPainter(self.image)
painter.setPen(QPen(self.myPenColor, self.myPenWidth, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin))
painter.drawLine(self.startPoint, self.endPoint)
painter.end()
self.startPoint = self.endPoint = None
self.update()
Note that you don't need to call update() within the resize event, as it's automatically called.
I also removed the unnecessary update rect calls, as it's almost useless in this case: specifying a rectangle in which the update should happen is usually done when very complex widgets are drawn (especially when lots of computations are executed to correctly draw everything and only a small part of the widget actually needs updates). In your case, it's almost more time consuming to compute the actual update rectangle than painting all the contents of the widget.
I think this page shows some really nice solutions for the problem of yours. For example, it shows how to implement a custom class which actually gives you a "drawing board":
class Canvas(QLabel):
def __init__(self):
super().__init__()
pixmap = QtGui.QPixmap(600, 300)
self.setPixmap(pixmap)
self.last_x, self.last_y = None, None
self.pen_color = QtGui.QColor('#000000')
def set_pen_color(self, c):
self.pen_color = QtGui.QColor(c)
def mouseMoveEvent(self, e):
if self.last_x is None: # First event.
self.last_x = e.x()
self.last_y = e.y()
return # Ignore the first time.
painter = QtGui.QPainter(self.pixmap())
p = painter.pen()
p.setWidth(1)
p.setColor(self.pen_color)
painter.setPen(p)
painter.drawLine(self.last_x, self.last_y, e.x(), e.y())
painter.end()
self.update()
# Update the origin for next time.
self.last_x = e.x()
self.last_y = e.y()
def mouseReleaseEvent(self, e):
self.last_x = None
self.last_y = None
You can use this Canvas class (or whatever name you would give it) everywhere you need. For example in the MainWindow:
class MainWindow(QMainWindow):
def __init__(self, parent=None):
QMainWindow.__init__(self, parent)
self.canvas = Canvas()
self.canvas.set_pen_color('#fffee5') # set the colour you want
self.setCentralWidget(self.canvas)
self.show()
Hope this could help! Happy coding! :)
I'm attempting to resolved an issue with a left over square after my snipping program is done snipping. I would like to delete any instance of the square drawing after the initial snip
.
Steps to replicate:
Select "mode" > select "snip" > drag rectangle and take a screen snip
Select "mode" > select "snip" > now observe the previous snip still has the rectangle on the screen (as shown in the picture)
My code:
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
from PIL import ImageGrab
from PyQt5.QtGui import QCursor
from PyQt5.QtWidgets import QApplication
class App(QtWidgets.QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
self.topMenu()
def initUI(self):
self.setWindowTitle("Lil Snippy")
self.setWindowIcon(QtGui.QIcon("assets/lilSnippyIcon.png"))
self.setGeometry(400, 300, 400, 300)
# QApplication.setOverrideCursor(Qt.WaitCursor)
def topMenu(self):
menubar = self.menuBar()
fileMenu = menubar.addMenu("File")
saveAct = QtWidgets.QAction(QtGui.QIcon("assets/saveIcon.png"), "Save", self)
saveAsAct = QtWidgets.QAction(
QtGui.QIcon("assets/saveAsIcon.png"), "Save As", self
)
modeMenu = menubar.addMenu("Mode")
snipAct = QtWidgets.QAction(QtGui.QIcon("assets/cameraIcon.png"), "Snip", self)
snipAct.setShortcut(QtGui.QKeySequence("F1"))
snipAct.triggered.connect(self.activateSnipping)
videoAct = QtWidgets.QAction(QtGui.QIcon("assets/videoIcon.png"), "Video", self)
videoAct.setShortcut("F2")
soundAct = QtWidgets.QAction(QtGui.QIcon("assets/audioIcon.png"), "Sound", self)
soundAct.setShortcut("F3")
autoAct = QtWidgets.QAction(
QtGui.QIcon("assets/automationIcon.png"), "Automation", self
)
autoAct.setShortcut("F4")
optionsMenu = menubar.addMenu("Options")
helpMenu = menubar.addMenu("Help")
helpAct = QtWidgets.QAction(QtGui.QIcon("assets/helpIcon.png"), "Help", self)
aboutAct = QtWidgets.QAction(QtGui.QIcon("assets/aboutIcon.png"), "About", self)
fileMenu.addAction(saveAct)
fileMenu.addAction(saveAsAct)
modeMenu.addAction(snipAct)
modeMenu.addAction(videoAct)
modeMenu.addAction(soundAct)
modeMenu.addAction(autoAct)
helpMenu.addAction(helpAct)
helpMenu.addAction(aboutAct)
self.snipper = SnippingWidget()
self.snipper.closed.connect(self.on_closed)
def activateSnipping(self):
self.snipper.showFullScreen()
QApplication.setOverrideCursor(QtCore.Qt.CrossCursor)
self.hide()
def on_closed(self):
self.show()
class SnippingWidget(QtWidgets.QMainWindow):
closed = QtCore.pyqtSignal()
def __init__(self, parent=None):
super(SnippingWidget, self).__init__(parent)
self.setAttribute(QtCore.Qt.WA_NoSystemBackground, True)
self.setAttribute(QtCore.Qt.WA_TranslucentBackground, True)
self.setStyleSheet("background:transparent;")
self.setWindowFlags(QtCore.Qt.FramelessWindowHint)
self.outsideSquareColor = "red"
self.squareThickness = 2
self.start_point = QtCore.QPoint()
self.end_point = QtCore.QPoint()
def mousePressEvent(self, event):
self.start_point = event.pos()
self.end_point = event.pos()
self.update()
def mouseMoveEvent(self, event):
self.end_point = event.pos()
self.update()
def mouseReleaseEvent(self, QMouseEvent):
r = QtCore.QRect(self.start_point, self.end_point).normalized()
self.hide()
img = ImageGrab.grab(bbox=r.getCoords())
img.save("snips/testImage.png")
QApplication.restoreOverrideCursor()
self.closed.emit()
def paintEvent(self, event):
trans = QtGui.QColor(22, 100, 233)
r = QtCore.QRectF(self.start_point, self.end_point).normalized()
qp = QtGui.QPainter(self)
trans.setAlphaF(0.2)
qp.setBrush(trans)
outer = QtGui.QPainterPath()
outer.addRect(QtCore.QRectF(self.rect()))
inner = QtGui.QPainterPath()
inner.addRect(r)
r_path = outer - inner
qp.drawPath(r_path)
qp.setPen(
QtGui.QPen(QtGui.QColor(self.outsideSquareColor), self.squareThickness)
)
trans.setAlphaF(0)
qp.setBrush(trans)
qp.drawRect(r)
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
application = App()
application.show()
sys.exit(app.exec_())
You have to reset self.start_point and self.end_point:
def mouseReleaseEvent(self, QMouseEvent):
r = QtCore.QRect(self.start_point, self.end_point).normalized()
self.hide()
img = ImageGrab.grab(bbox=r.getCoords())
img.save("snips/testImage.png")
QApplication.restoreOverrideCursor()
self.closed.emit()
self.start_point = QtCore.QPoint()
self.end_point = QtCore.QPoint()
I'm in the process of converting my successful screen snipping program from Tkinter to PYQT5. My question is how to create a fully transparent snipping area (a dynamically updating square region would be nice). The outside of the square will be semi-opaque. I've looked all over stack overflow and the internet and could not find an example of this (others are not a fully transparent drawing window). I've attached my code and a picture example of what I am looking for. The "SnippingWidget" is the class that does the snipping logic.
import sys
from PyQt5 import QtCore, QtGui
from PyQt5.QtWidgets import QMainWindow, QApplication, QAction, QWidget
from PyQt5.QtGui import QIcon, QKeySequence
from PIL import ImageGrab
class App(QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
self.topMenu()
def initUI(self):
self.setWindowTitle('Lil Snippy')
self.setWindowIcon(QIcon('assets/lilSnippyIcon.png'))
self.setGeometry(400, 300, 400, 300)
self.show()
def topMenu(self):
menubar = self.menuBar()
fileMenu = menubar.addMenu('File')
saveAct = QAction(QIcon('assets/saveIcon.png'), 'Save', self)
saveAsAct = QAction(QIcon('assets/saveAsIcon.png'), 'Save As', self)
modeMenu = menubar.addMenu('Mode')
snipAct = QAction(QIcon('assets/cameraIcon.png'), 'Snip', self)
snipAct.setShortcut(QKeySequence('F1'))
snipAct.triggered.connect(self.activateSnipping)
videoAct = QAction(QIcon('assets/videoIcon.png'), 'Video', self)
videoAct.setShortcut('F2')
soundAct = QAction(QIcon('assets/audioIcon.png'), 'Sound', self)
soundAct.setShortcut('F3')
autoAct = QAction(QIcon('assets/automationIcon.png'), 'Automation', self)
autoAct.setShortcut('F4')
helpMenu = menubar.addMenu('Help')
helpAct = QAction(QIcon('assets/helpIcon.png'), 'Help', self)
aboutAct = QAction(QIcon('assets/aboutIcon.png'), 'About', self)
fileMenu.addAction(saveAct)
fileMenu.addAction(saveAsAct)
modeMenu.addAction(snipAct)
modeMenu.addAction(videoAct)
modeMenu.addAction(soundAct)
modeMenu.addAction(autoAct)
helpMenu.addAction(helpAct)
helpMenu.addAction(aboutAct)
def activateSnipping(self):
print("yes")
self.Snipper = SnippingWidget()
application.hide()
class SnippingWidget(QMainWindow):
def __init__(self, parent = None):
super(SnippingWidget, self).__init__(parent)
self.setStyleSheet("background-color: transparent;")
self.setWindowOpacity(.2)
self.showFullScreen()
self.outsideSquareColor = 'red'
self.squareThickness = 4
self.startX = None
self.startY = None
self.endX = None
self.endY = None
self.begin = QtCore.QPoint()
self.end = QtCore.QPoint()
def mousePressEvent(self, event):
self.begin = event.pos()
self.end = self.begin
self.startX = event.x()
self.startY = event.y()
self.update()
def mouseReleaseEvent(self, QMouseEvent):
self.destroy()
x1 = min(self.begin.x(), self.end.x())
y1 = min(self.begin.y(), self.end.y())
x2 = max(self.begin.x(), self.end.x())
y2 = max(self.begin.y(), self.end.y())
img = ImageGrab.grab(bbox=(x1, y1, x2, y2))
img.save('snips/testImage.png')
application.show()
def mouseMoveEvent(self, event):
self.end = event.pos()
self.update()
def paintEvent(self, event):
qp = QtGui.QPainter(self)
qp.setPen(QtGui.QPen(QtGui.QColor('red'), self.squareThickness))
trans = QtGui.QColor(255,255,255,255)
qp.setBrush(trans)
rect = QtCore.QRectF(self.begin, self.end)
qp.drawRect(rect)
if __name__ == '__main__':
app = QApplication(sys.argv)
application = App()
sys.exit(app.exec_())
You have to use QPainterPath to subtract the rectangle from the window with the selected rectangle:
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
from PIL import ImageGrab
class App(QtWidgets.QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
self.topMenu()
def initUI(self):
self.setWindowTitle("Lil Snippy")
self.setWindowIcon(QtGui.QIcon("assets/lilSnippyIcon.png"))
self.setGeometry(400, 300, 400, 300)
def topMenu(self):
menubar = self.menuBar()
fileMenu = menubar.addMenu("File")
saveAct = QtWidgets.QAction(QtGui.QIcon("assets/saveIcon.png"), "Save", self)
saveAsAct = QtWidgets.QAction(
QtGui.QIcon("assets/saveAsIcon.png"), "Save As", self
)
modeMenu = menubar.addMenu("Mode")
snipAct = QtWidgets.QAction(QtGui.QIcon("assets/cameraIcon.png"), "Snip", self)
snipAct.setShortcut(QtGui.QKeySequence("F1"))
snipAct.triggered.connect(self.activateSnipping)
videoAct = QtWidgets.QAction(QtGui.QIcon("assets/videoIcon.png"), "Video", self)
videoAct.setShortcut("F2")
soundAct = QtWidgets.QAction(QtGui.QIcon("assets/audioIcon.png"), "Sound", self)
soundAct.setShortcut("F3")
autoAct = QtWidgets.QAction(
QtGui.QIcon("assets/automationIcon.png"), "Automation", self
)
autoAct.setShortcut("F4")
helpMenu = menubar.addMenu("Help")
helpAct = QtWidgets.QAction(QtGui.QIcon("assets/helpIcon.png"), "Help", self)
aboutAct = QtWidgets.QAction(QtGui.QIcon("assets/aboutIcon.png"), "About", self)
fileMenu.addAction(saveAct)
fileMenu.addAction(saveAsAct)
modeMenu.addAction(snipAct)
modeMenu.addAction(videoAct)
modeMenu.addAction(soundAct)
modeMenu.addAction(autoAct)
helpMenu.addAction(helpAct)
helpMenu.addAction(aboutAct)
self.snipper = SnippingWidget()
self.snipper.closed.connect(self.on_closed)
def activateSnipping(self):
self.snipper.showFullScreen()
self.hide()
def on_closed(self):
self.snipper.hide()
self.show()
class SnippingWidget(QtWidgets.QMainWindow):
closed = QtCore.pyqtSignal()
def __init__(self, parent=None):
super(SnippingWidget, self).__init__(parent)
self.setStyleSheet("background-color: transparent;")
self.setWindowOpacity(0.2)
self.outsideSquareColor = "red"
self.squareThickness = 4
self.start_point = QtCore.QPoint()
self.end_point = QtCore.QPoint()
def mousePressEvent(self, event):
self.start_point = event.pos()
self.end_point = event.pos()
self.update()
def mouseMoveEvent(self, event):
self.end_point = event.pos()
self.update()
def mouseReleaseEvent(self, QMouseEvent):
r = QtCore.QRect(self.start_point, self.end_point).normalized()
img = ImageGrab.grab(bbox=r.getCoords())
img.save("snips/testImage.png")
self.closed.emit()
def paintEvent(self, event):
qp = QtGui.QPainter(self)
qp.setPen(
QtGui.QPen(QtGui.QColor(self.outsideSquareColor), self.squareThickness)
)
trans = QtGui.QColor(255, 255, 255, 255)
qp.setBrush(trans)
outer = QtGui.QPainterPath()
outer.addRect(QtCore.QRectF(self.rect()))
inner = QtGui.QPainterPath()
inner.addRect(QtCore.QRectF(self.start_point, self.end_point).normalized())
r = outer - inner
qp.drawPath(r)
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
application = App()
application.show()
sys.exit(app.exec_())
Update:
class SnippingWidget(QtWidgets.QMainWindow):
closed = QtCore.pyqtSignal()
def __init__(self, parent=None):
super(SnippingWidget, self).__init__(parent)
self.setAttribute(QtCore.Qt.WA_NoSystemBackground, True)
self.setAttribute(QtCore.Qt.WA_TranslucentBackground, True)
self.setStyleSheet("background:transparent;")
self.setWindowFlags(QtCore.Qt.FramelessWindowHint)
self.outsideSquareColor = "red"
self.squareThickness = 4
self.start_point = QtCore.QPoint()
self.end_point = QtCore.QPoint()
def mousePressEvent(self, event):
self.start_point = event.pos()
self.end_point = event.pos()
self.update()
def mouseMoveEvent(self, event):
self.end_point = event.pos()
self.update()
def mouseReleaseEvent(self, QMouseEvent):
r = QtCore.QRect(self.start_point, self.end_point).normalized()
img = ImageGrab.grab(bbox=r.getCoords())
img.save("snips/testImage.png")
self.closed.emit()
def paintEvent(self, event):
trans = QtGui.QColor(255, 255, 255)
r = QtCore.QRectF(self.start_point, self.end_point).normalized()
qp = QtGui.QPainter(self)
trans.setAlphaF(0.2)
qp.setBrush(trans)
outer = QtGui.QPainterPath()
outer.addRect(QtCore.QRectF(self.rect()))
inner = QtGui.QPainterPath()
inner.addRect(r)
r_path = outer - inner
qp.drawPath(r_path)
qp.setPen(
QtGui.QPen(QtGui.QColor(self.outsideSquareColor), self.squareThickness)
)
trans.setAlphaF(0)
qp.setBrush(trans)
qp.drawRect(r)
I want to draw polyline with mouse event. But I can't set endpoints by clicking, or choose pen type. I want to draw linear lines, but when i write this code it only shows dots instead of drawing a line. Here is my code:
import sys
from PyQt5 import QtWidgets, QtCore
from PyQt5.QtGui import QPainter, QBrush, QColor, QPen, QPainterPath
from PyQt5.QtWidgets import QLabel, QGraphicsScene, QGraphicsView
class MyWidget(QtWidgets.QWidget):
def __init__(self):
super().__init__()
self.begin = QtCore.QPoint()
self.end = QtCore.QPoint()
self.beginList = []
self.endList = []
self.initUI()
def initUI(self):
self.setGeometry(200, 200, 1000, 500)
self.label = QLabel(self)
self.label.resize(500, 40)
self.show()
def paintEvent(self, event):
qp = QPainter(self)
for i,j in zip(self.beginList, self.endList):
qp.drawLines(QtCore.QLineF(i,j))
def mouseMoveEvent(self, event):
self.begin = event.pos()
self.end = event.pos()
self.beginList.append(self.begin)
self.endList.append(self.end)
self.label.setText('Coordinates: ( %d : %d )' % (event.x(), event.y()))
self.update()
def mouseReleaseEvent(self, event):
self.begin = event.pos()
self.end = event.pos()
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
window = MyWidget()
window.resize(800,600)
sys.exit(app.exec_())
If the OP code is analyzed, the starting point and the end point coincide, so when drawing a line between 2 points of the same location, only one point will be drawn. The logic is to join the point obtained in the i-th step with the (i+1)-th point.
To do the above the simplest thing is to use a QPainterPath:
import sys
from PyQt5 import QtWidgets, QtGui, QtCore
class MyWidget(QtWidgets.QWidget):
def __init__(self):
super().__init__()
self.initUI()
self.paths = []
def initUI(self):
self.setGeometry(200, 200, 1000, 500)
self.label = QtWidgets.QLabel(self)
self.show()
def paintEvent(self, event):
qp = QtGui.QPainter(self)
for path in self.paths:
qp.drawPath(path)
def mousePressEvent(self, event):
path = QtGui.QPainterPath()
path.moveTo(event.pos())
self.paths.append(path)
super().mousePressEvent(event)
def mouseMoveEvent(self, event):
self.paths[-1].lineTo(event.pos())
self.label.setText('Coordinates: ( %d : %d )' % (event.x(), event.y()))
self.label.adjustSize()
self.update()
super().mouseMoveEvent(event)
def mouseReleaseEvent(self, event):
self.paths[-1].lineTo(event.pos())
self.update()
super().mouseReleaseEvent(event)
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
window = MyWidget()
window.resize(800, 600)
sys.exit(app.exec_())
The title basically says it all. I want to create an image that I can drag around inside a window. My code so far does all that but for some reason, the image appears really small even though, I used the scaled() function to resize it. Also, if I change the values inside the scaled() function, the image disappears.
from PySide.QtGui import *
from PySide.QtCore import *
import sys
class Label(QLabel):
def __init__(self, title, parent):
super(Label, self).__init__(title, parent)
self.setup()
def setup(self):
folder_pic = QPixmap("path")
folder_size = folder_pic.scaled(64, 64)
self.label = QLabel(self)
self.label.setPixmap(folder_size)
def mouseMoveEvent(self, e):
if e.buttons() != Qt.LeftButton:
return
mimeData = QMimeData(self)
drag = QDrag(self)
drag.setMimeData(mimeData)
drag.setHotSpot(e.pos() - self.rect().topLeft())
dropAction = drag.start(Qt.MoveAction)
class Example(QWidget):
def __init__(self):
super(Example, self).__init__()
self.initUI()
def initUI(self):
self.setAcceptDrops(True)
self.button = Label("", 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()
self.button.move(position)
e.setDropAction(Qt.MoveAction)
e.accept()
if __name__ == "__main__":
app = QApplication(sys.argv)
mywin = Example()
mywin.show()
sys.exit(app.exec_())
My code is based on this tutorial http://zetcode.com/gui/pysidetutorial/dragdrop/.
You set a pixmap on the drag object:
drag.setPixmap(self.pixmap())
But for that to work, you will also need this fix:
def setup(self):
folder_pic = QPixmap("path")
folder_size = folder_pic.scaled(64, 64)
self.setPixmap(folder_size)