I have this app written in pyqt. You can view the source at http://www.pasteall.org/62739/python It takes screen shots of the desktop. what I want to know is how to make it also take a screen shot of a certain area on the screen like window's snipping tool can do (http://sjcblogs.sanjac.edu/its/files/2011/09/Snipping-Tool-selection-types1.jpg and gilsmethod.wpengine.netdna-cdn.com/images/snipping-tool-windows-73.png). How do I write this?
Thank you in advance!
You should use
img = QPixmap.grabWindow(QApplication.desktop().winId(), x, y, width, height)
The pyqt distro has a very good python example of screeshoting with pyqt. The C++ code of the example, easily converted to Python, is at http://doc.qt.io/qt-4.8/qt-desktop-screenshot-example.html
Install following packages:
pip install pillow opencv-python pyside2
Run the following code:
import sys
from PySide2.QtCore import *
from PySide2.QtGui import *
from PySide2.QtWidgets import *
import numpy as np
import cv2
from PIL import ImageGrab
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
if not MainWindow.objectName():
MainWindow.setObjectName(u"MainWindow")
MainWindow.resize(1000, 1000)
sizePolicy = QSizePolicy(QSizePolicy.Maximum, QSizePolicy.Maximum)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(MainWindow.sizePolicy().hasHeightForWidth())
MainWindow.setSizePolicy(sizePolicy)
MainWindow.setMinimumSize(QSize(1000, 1000))
MainWindow.setMaximumSize(QSize(16777215, 16777215))
MainWindow.setTabShape(QTabWidget.Rounded)
self.centralwidget = QWidget(MainWindow)
self.centralwidget.setObjectName(u"centralwidget")
sizePolicy1 = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred)
sizePolicy1.setHorizontalStretch(0)
sizePolicy1.setVerticalStretch(0)
sizePolicy1.setHeightForWidth(self.centralwidget.sizePolicy().hasHeightForWidth())
self.centralwidget.setSizePolicy(sizePolicy1)
self.centralwidget.setMinimumSize(QSize(1000, 1000))
self.gridLayout = QGridLayout(self.centralwidget)
self.gridLayout.setObjectName(u"gridLayout")
self.pushButton_area = QPushButton(self.centralwidget)
self.pushButton_area.setObjectName(u"pushButton_area")
self.pushButton_area.setMinimumSize(QSize(800, 0))
self.gridLayout.addWidget(self.pushButton_area, 0, 0, 1, 1)
self.label = QLabel(self.centralwidget)
self.label.setObjectName(u"label")
sizePolicy2 = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
sizePolicy2.setHorizontalStretch(0)
sizePolicy2.setVerticalStretch(0)
sizePolicy2.setHeightForWidth(self.label.sizePolicy().hasHeightForWidth())
self.label.setSizePolicy(sizePolicy2)
self.label.setMinimumSize(QSize(800, 800))
self.label.setMaximumSize(QSize(4096, 4096))
self.gridLayout.addWidget(self.label, 2, 0, 2, 1)
self.pushButton_full = QPushButton(self.centralwidget)
self.pushButton_full.setObjectName(u"pushButton_full")
self.pushButton_full.setMinimumSize(QSize(800, 0))
self.gridLayout.addWidget(self.pushButton_full, 1, 0, 1, 1)
MainWindow.setCentralWidget(self.centralwidget)
self.retranslateUi(MainWindow)
QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
MainWindow.setWindowTitle(QCoreApplication.translate("MainWindow", u"Snipping Tool", None))
MainWindow.setAccessibleName(QCoreApplication.translate("MainWindow", u"Snipping Tool", None))
self.pushButton_area.setText(QCoreApplication.translate("MainWindow", u"Select Area", None))
self.pushButton_full.setText(QCoreApplication.translate("MainWindow", u"Fullscreen", None))
# Refer to https://github.com/harupy/snipping-tool
class SnippingWidget(QWidget):
is_snipping = False
def __init__(self, parent=None, app=None):
super(SnippingWidget, self).__init__()
self.parent = parent
self.setWindowFlags(Qt.WindowStaysOnTopHint)
self.screen = app.primaryScreen()
self.setGeometry(0, 0, self.screen.size().width(), self.screen.size().height())
self.begin = QPoint()
self.end = QPoint()
self.onSnippingCompleted = None
def fullscreen(self):
img = ImageGrab.grab(bbox=(0, 0, self.screen.size().width(), self.screen.size().height()))
try:
img = cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR)
except:
img = None
if self.onSnippingCompleted is not None:
self.onSnippingCompleted(img)
def start(self):
SnippingWidget.is_snipping = True
self.setWindowOpacity(0.3)
QApplication.setOverrideCursor(QCursor(Qt.CrossCursor))
self.show()
def paintEvent(self, event):
if SnippingWidget.is_snipping:
brush_color = (128, 128, 255, 100)
lw = 3
opacity = 0.3
else:
self.begin = QPoint()
self.end = QPoint()
brush_color = (0, 0, 0, 0)
lw = 0
opacity = 0
self.setWindowOpacity(opacity)
qp = QPainter(self)
qp.setPen(QPen(QColor('black'), lw))
qp.setBrush(QColor(*brush_color))
rect = QRectF(self.begin, self.end)
qp.drawRect(rect)
def mousePressEvent(self, event):
self.begin = event.pos()
self.end = self.begin
self.update()
def mouseMoveEvent(self, event):
self.end = event.pos()
self.update()
def mouseReleaseEvent(self, event):
SnippingWidget.is_snipping = False
QApplication.restoreOverrideCursor()
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())
self.repaint()
QApplication.processEvents()
img = ImageGrab.grab(bbox=(x1, y1, x2, y2))
try:
img = cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR)
except:
img = None
if self.onSnippingCompleted is not None:
self.onSnippingCompleted(img)
self.close()
class MainWindow(QMainWindow):
useQThread = True
def __init__(self):
super(MainWindow, self).__init__()
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
self.setAcceptDrops(True)
self.snippingWidget = SnippingWidget(app=QApplication.instance())
self.snippingWidget.onSnippingCompleted = self.onSnippingCompleted
self.ui.pushButton_area.clicked.connect(self.snipArea)
self.ui.pushButton_full.clicked.connect(self.snipFull)
self._pixmap = None
def onSnippingCompleted(self, frame):
self.setWindowState(Qt.WindowActive)
if frame is None:
return
image = QImage(frame, frame.shape[1], frame.shape[0], frame.strides[0], QImage.Format_RGB888)
pixmap = QPixmap.fromImage(image)
self._pixmap = self.resizeImage(pixmap)
self.ui.label.setPixmap(self._pixmap)
def snipArea(self):
self.setWindowState(Qt.WindowMinimized)
self.snippingWidget.start()
def snipFull(self):
self.setWindowState(Qt.WindowMinimized)
self.snippingWidget.fullscreen()
def dragEnterEvent(self, event):
event.acceptProposedAction()
def dropEvent(self, event):
urls = event.mimeData().urls()
filename = urls[0].toLocalFile()
self.loadFile(filename)
self.decodeFile(filename)
event.acceptProposedAction()
def resizeImage(self, pixmap):
lwidth = self.ui.label.width()
pwidth = pixmap.width()
lheight = self.ui.label.height()
pheight = pixmap.height()
wratio = pwidth * 1.0 / lwidth
hratio = pheight * 1.0 / lheight
if pwidth > lwidth or pheight > lheight:
if wratio > hratio:
lheight = pheight / wratio
else:
lwidth = pwidth / hratio
scaled_pixmap = pixmap.scaled(lwidth, lheight)
return scaled_pixmap
else:
return pixmap
def showMessageBox(self, title, content):
msgBox = QMessageBox()
msgBox.setWindowTitle(title)
msgBox.setText(content)
msgBox.exec_()
def closeEvent(self, event):
msg = "Close the app?"
reply = QMessageBox.question(self, 'Message',
msg, QMessageBox.Yes, QMessageBox.No)
if reply == QMessageBox.Yes:
event.accept()
else:
event.ignore()
def main():
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
Related
I have a problem using simpledialog.askstring from tkinter, it opens two pop up windows, one of them is the regular one to input a value, but the other is a blank window that freezes completely and you have to force the cloosure of the window, enter image description hereas shown in the image in the link. I'm using spyder.
What could be happening?
This is what I have so far:
from PyQt5 import QtWidgets, QtCore, QtGui
from PyQt5.QtCore import pyqtSignal, QObject
from PyQt5.QtWidgets import QApplication, QMainWindow, QComboBox,
QLabel, QPushButton, QGroupBox
import tkinter as tk
from tkinter import simpledialog
from PIL import ImageGrab
import sys
import cv2
import numpy as np
# import imageToString
import pyperclip
import webbrowser
import pytesseract
pytesseract.pytesseract.tesseract_cmd =
r"C:\Users\amc\AppData\Local\Programs\Tesseract-OCR\tesseract.exe"
class Communicate(QObject):
snip_saved = pyqtSignal()
class MyWindow(QMainWindow):
def __init__(self, parent=None):
super(MyWindow, self).__init__()
self.win_width = 340
self.win_height = 200
self.setGeometry(50, 50, self.win_width, self.win_height)
self.setWindowTitle("PSD Generator")
self.initUI()
def initUI(self):
#Define buttons
self.searchOpen = QPushButton(self)
self.searchOpen.setText("Digitilize Graph")
self.searchOpen.move(10,75)
self.searchOpen.setFixedSize(150,40)
self.searchOpen.clicked.connect(self.snip_graph_clicked)
self.copyPartNum = QPushButton(self)
self.copyPartNum.setText("Snip Table")
self.copyPartNum.move((self.win_width/2)+10, 75)
self.copyPartNum.setFixedSize(150,40)
self.copyPartNum.clicked.connect(self.snip_table_clicked)
self.notificationBox = QGroupBox("Notification Box", self)
self.notificationBox.move(10,135)
self.notificationBox.setFixedSize(self.win_width-20,55)
self.notificationText = QLabel(self)
self.notificationText.move(20, 145)
self.reset_notif_text()
def snip_graph_clicked(self):
self.snipWin = SnipWidget(False, True, self)
self.snipWin.notification_signal.connect(self.reset_notif_text)
self.snipWin.show()
self.notificationText.setText("Snipping... Press ESC to quit snipping")
self.update_notif()
def snip_table_clicked(self):
self.snipWin = SnipWidget(True, False, self)
self.snipWin.notification_signal.connect(self.reset_notif_text)
self.snipWin.show()
self.notificationText.setText("Snipping... Press ESC to quit snipping")
self.update_notif()
def reset_notif_text(self):
self.notificationText.setText("Idle...")
self.update_notif()
def define_notif_text(self, msg):
print('notification was sent')
self.notificationText.setText('notification was sent')
self.update_notif()
def update_notif(self):
self.notificationText.move(20, 155)
self.notificationText.adjustSize()
class SnipWidget(QMainWindow):
notification_signal = pyqtSignal()
def __init__(self, copy_table, scan_graph, parent):
super(SnipWidget, self).__init__()
self.copy_table = copy_table
self.scan_graph = scan_graph
root = tk.Tk()# instantiates window
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()
self.setGeometry(0, 0, screen_width, screen_height)
self.setWindowTitle(' ')
self.begin = QtCore.QPoint()
self.end = QtCore.QPoint()
self.setWindowOpacity(0.3)
self.is_snipping = False
QtWidgets.QApplication.setOverrideCursor(
QtGui.QCursor(QtCore.Qt.CrossCursor)
)
self.setWindowFlags(QtCore.Qt.FramelessWindowHint)
self.c = Communicate()
self.show()
if self.copy_table == True:
# the input dialog
BH_Ref = simpledialog.askstring(title="New PSD",prompt="Borehole Number Ref:")
Depth = simpledialog.askstring(title="New PSD",prompt="Sample depth (m):")
self.c.snip_saved.connect(self.searchAndOpen)
if self.scan_graph == True:
# the input dialog
BH_Ref = simpledialog.askstring(title="New PSD",prompt="Borehole Number Ref:")
Depth = simpledialog.askstring(title="New PSD",prompt="Sample depth (m):")
self.c.snip_saved.connect(self.IdAndCopy)
def paintEvent(self, event):
if self.is_snipping:
brush_color = (0, 0, 0, 0)
lw = 0
opacity = 0
else:
brush_color = (128, 128, 255, 128)
lw = 3
opacity = 0.3
self.setWindowOpacity(opacity)
qp = QtGui.QPainter(self)
qp.setPen(QtGui.QPen(QtGui.QColor('black'), lw))
qp.setBrush(QtGui.QColor(*brush_color))
qp.drawRect(QtCore.QRect(self.begin, self.end))
def keyPressEvent(self, event):
if event.key() == QtCore.Qt.Key_Escape:
print('Quit')
QtWidgets.QApplication.restoreOverrideCursor();
self.notification_signal.emit()
self.close()
event.accept()
def mousePressEvent(self, event):
self.begin = event.pos()
self.end = self.begin
self.update()
def mouseMoveEvent(self, event):
self.end = event.pos()
self.update()
def mouseReleaseEvent(self, event):
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())
self.is_snipping = True
self.repaint()
QtWidgets.QApplication.processEvents()
img = ImageGrab.grab(bbox=(x1, y1, x2, y2))
self.is_snipping = False
self.repaint()
QtWidgets.QApplication.processEvents()
img = cv2.cvtColor(np.array(img), cv2.COLOR_BGR2GRAY)
self.snipped_image = img
QtWidgets.QApplication.restoreOverrideCursor();
self.c.snip_saved.emit()
self.close()
self.msg = 'snip complete'
self.notification_signal.emit()
def searchAndOpen(self):
img_str = self.imgToStr(self.snipped_image)
msg_str = f'Text in snip is {img_str}'
def IdAndCopy(self):
img_str = self.imgToStr(self.snipped_image)
pyperclip.copy(img_str)
def find_str(self, image_data):
img = image_data
h,w = np.shape(img)
asp_ratio = float(w/h)
img_width = 500
img_height = int(round(img_width/asp_ratio))
desired_image_size = (img_width,img_height)
img_resized = cv2.resize(img, desired_image_size)
imgstr = str(pytesseract.image_to_string(img_resized))
print(imgstr)
return imgstr
def imgToStr(self, image):
# img_str = imageToString.main(image)
img_str = self.find_str(image)
return img_str
def window():
app = QApplication(sys.argv)
win = MyWindow()
win.show()
sys.exit(app.exec_())
window()
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)
This question already has answers here:
Painting background on QGraphicsView using drawBackground
(1 answer)
How to enable Pan and Zoom in a QGraphicsView
(3 answers)
How to put an image in QGraphicsView's scrollbar area?
(1 answer)
Closed 3 years ago.
I'm wondering how to set QgraphicsView's background Image.
In this painter program, the background is just white color.
I want to load some image(jpg, png, .. whatever) and set it as painter's background.
and after painting it, I want to just save painting (not include background, just what i painted.)
how can i do this? please help me.
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('지우개')
left.addWidget(gb)
hbox = QHBoxLayout()
gb.setLayout(hbox)
self.checkbox = QCheckBox('지우개')
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):
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()
# 색상이 유효한 값이면 참, QFrame에 색 적용
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.setRenderHint(QPainter.HighQualityAntialiasing)
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 open(self):
fileName, _ = QFileDialog.getOpenFileName(self, "Open File",
QDir.currentPath())
if fileName:
image = QImage(fileName)
if image.isNull():
QMessageBox.information(self, "Image Viewer",
"Cannot load %s." % fileName)
return
self.imageLabel.setPixmap(QPixmap.fromImage(image))
self.scaleFactor = 1.0
self.printAct.setEnabled(True)
self.fitToWindowAct.setEnabled(True)
self.updateActions()
if not self.fitToWindowAct.isChecked():
self.imageLabel.adjustSize()
if __name__ == '__main__':
app = QApplication(sys.argv)
w = CWidget()
w.show()
sys.exit(app.exec_())
You can create an instance of QGraphicsPixmapItem and add it to the scene, here is an example:
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('지우개')
left.addWidget(gb)
hbox = QHBoxLayout()
gb.setLayout(hbox)
self.checkbox = QCheckBox('지우개')
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):
self.view.stretch(state)
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()
# 색상이 유효한 값이면 참, QFrame에 색 적용
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)')
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_())
I would like explaining what is it I want to achieve, and what is it, that does not work probably. When a user draw a rectangular or rounded shape, a ring inside rounded shape, and a rectangular ring with rounded edge inside rectangular shape want to be drawn. So far I have achieved with my code... shown below
As shown above, inner rectangular should be subtracted from outer rectangular. And edges should be rounded.
What I want to achieve and similar for rounded shape
The code :
from PyQt5 import QtCore, QtGui, QtWidgets
class Foo(QtWidgets.QWidget):
def __init__(self, parent=None):
super(Foo, self).__init__(parent)
self.setGeometry(QtCore.QRect(200, 100, 800, 800))
self.button = Button()
self.paint = Createpaintwidget()
self.button.valuesChanged.connect(self.paint.set_size_squares)
self.button.valueChanged.connect(self.paint.set_size_round)
self.lay = QtWidgets.QVBoxLayout(self)
self.lay.addWidget(self.paint)
self.lay.addWidget(self.button)
class Createpaintwidget(QtWidgets.QWidget):
def __init__(self):
super().__init__()
self.sizeHint()
self.setBackgroundRole(QtGui.QPalette.Base)
self.setAutoFillBackground(True)
self._size = QtCore.QSizeF()
self._path = QtGui.QPainterPath()
self._rect = QtCore.QRectF()
self._type = QtGui.QRegion.Rectangle
self._factor = 1.0
self._sizeouter = QtCore.QSizeF()
self._rectouter = QtCore.QRectF()
self._sizeinner = QtCore.QSizeF()
self._rectinner = QtCore.QRectF()
self._pos = QtCore.QPointF()
self._initial_flag = False
fnt = self.font()
fnt.setPointSize(20)
self.setFont(fnt)
print(self._size, self._rect, self._type, self._pos)
def showEvent(self, event):
if not self._initial_flag:
self._pos = self.rect().center()
self._initial_flag = True
#QtCore.pyqtSlot(int, int)
def set_size_squares(self, w, h):
cb, ct, yb = 25, 25, 8
self._path = QtGui.QPainterPath()
self._size = QtCore.QSizeF(w, h)
self._sizeouter = QtCore.QSizeF(w-cb, h-ct)
self._sizeinner = QtCore.QSizeF(w-cb-yb, h-ct-yb)
self._type = QtGui.QRegion.Rectangle
self.updatePath()
print(self._size, self._rect, self._type, self._pos)
#QtCore.pyqtSlot(int)
def set_size_round(self, v):
cb, yb = 25, 8
self._path = QtGui.QPainterPath()
self._size = QtCore.QSizeF(v, v)
self._sizeouter = QtCore.QSizeF(v-cb, v-cb)
self._sizeinner = QtCore.QSizeF(v-cb-yb, v-cb-yb)
self._type = QtGui.QRegion.Ellipse
self.updatePath()
def paintEvent(self, event):
pen = QtGui.QPen()
brush = QtGui.QBrush(QtCore.Qt.black)
painter = QtGui.QPainter(self)
painter.setRenderHint(QtGui.QPainter.Antialiasing)
painter.setPen(pen)
painter.setBrush(brush)
painter.translate(self.rect().center())
painter.scale(self._factor, self._factor)
painter.translate(-self.rect().center())
painter.translate(self._pos)
painter.drawPath(self._path)
if self._type == QtGui.QRegion.Rectangle:
painter.fillRect(self._rectouter, QtGui.QBrush(QtCore.Qt.cyan, QtCore.Qt.SolidPattern))
painter.setBrush(QtGui.QBrush(QtCore.Qt.NoBrush))
painter.drawRect(self._rectouter)
painter.fillRect(self._rect, QtGui.QBrush(QtCore.Qt.gray, QtCore.Qt.Dense7Pattern))
painter.setBrush(QtGui.QBrush(QtCore.Qt.NoBrush))
painter.drawRect(self._rect)
painter.fillRect(self._rectinner, QtGui.QBrush(QtCore.Qt.gray, QtCore.Qt.Dense7Pattern))
painter.setBrush(QtGui.QBrush(QtCore.Qt.NoBrush))
painter.drawRect(self._rectinner)
elif self._type == QtGui.QRegion.Ellipse:
painter.setBrush(QtGui.QBrush(QtCore.Qt.gray, QtCore.Qt.Dense7Pattern))
painter.drawEllipse(self._rect)
painter.setBrush(QtGui.QBrush(QtCore.Qt.gray, QtCore.Qt.SolidPattern))
painter.drawEllipse(self._rectouter)
painter.setBrush(QtGui.QBrush(QtCore.Qt.gray, QtCore.Qt.Dense7Pattern))
painter.drawEllipse(self._rectinner)
def mousePressEvent(self, event):
QtWidgets.QApplication.setOverrideCursor(QtGui.QCursor(QtCore.Qt.OpenHandCursor))
self._initial_pos = event.pos()
super().mousePressEvent(event)
def mouseMoveEvent(self, event):
delta = event.pos() - self._initial_pos
self._path.translate(delta)
self._rect.translate(delta)
self._rectinner.translate(delta)
self._rectouter.translate(delta)
self.update()
self._initial_pos = event.pos()
super().mouseMoveEvent(event)
def mouseReleaseEvent(self, event):
QtWidgets.QApplication.restoreOverrideCursor()
super().mouseReleaseEvent(event)
def updatePath(self):
fm = QtGui.QFontMetrics(self.font())
r = QtCore.QRectF(QtCore.QPointF(), self._size)
ro = QtCore.QRectF(QtCore.QPointF(), self._sizeouter)
ri = QtCore.QRectF(QtCore.QPointF(), self._sizeinner)
r.moveCenter(QtCore.QPointF())
ro.moveCenter(QtCore.QPointF())
ri.moveCenter(QtCore.QPointF())
r.moveCenter(QtCore.QPointF())
self._rectouter = QtCore.QRectF(ro)
self._rectinner = QtCore.QRectF(ri)
self._rect = QtCore.QRectF(r)
self._path.moveTo(QtCore.QPointF())
self.update()
def wheelEvent(self, event):
self._factor *= 1.01**(event.angleDelta().y()/15.0)
self.update()
super().wheelEvent(event)
class Button(QtWidgets.QWidget):
valueChanged = QtCore.pyqtSignal(int)
valuesChanged = QtCore.pyqtSignal(int,int)
def __init__(self, parent=None):
super(Button, self).__init__(parent)
roundbutton = QtWidgets.QPushButton('Round')
squarebutton = QtWidgets.QPushButton('Square')
Alay = QtWidgets.QVBoxLayout(self)
Alay.addWidget(roundbutton)
Alay.addWidget(squarebutton)
self.value = QtWidgets.QLabel()
roundbutton.clicked.connect(self.getbuttonfunc)
squarebutton.clicked.connect(self.sqaurebuttonfunc)
#QtCore.pyqtSlot()
def getbuttonfunc(self):
number, ok = QtWidgets.QInputDialog.getInt(self, self.tr("Set Number"),
self.tr("Input:"), 1, 1)
if ok:
self.valueChanged.emit(number)
#QtCore.pyqtSlot()
def sqaurebuttonfunc(self):
number, ok = QtWidgets.QInputDialog.getInt(self, self.tr("Set Number"),
self.tr("Input:"), 1, 1)
if ok:
self.valuesChanged.emit(number, number)
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
w = Foo()
w.show()
sys.exit(app.exec_())
For these cases it is better to use a QPainterPathStroker and pass it a QPainterPath that I have the round rectangle with addRoundedRect():
def paintEvent(self, event):
pen = QtGui.QPen()
brush = QtGui.QBrush(QtCore.Qt.black)
painter = QtGui.QPainter(self)
painter.setRenderHint(QtGui.QPainter.Antialiasing)
painter.setPen(pen)
painter.setBrush(brush)
painter.translate(self.rect().center())
painter.scale(self._factor, self._factor)
painter.translate(-self.rect().center())
painter.translate(self._pos)
painter.drawPath(self._path)
S = (self._rectouter.size() + self._rectinner.size())/2
s = (self._rectouter.size() - self._rectinner.size())/2
r = QtCore.QRectF(QtCore.QPointF(), S)
r.moveCenter(self._rectouter.center())
path = QtGui.QPainterPath()
painter.setBrush(QtGui.QBrush(QtCore.Qt.gray, QtCore.Qt.Dense7Pattern))
if self._type == QtGui.QRegion.Rectangle:
painter.drawRect(self._rect)
path.addRoundedRect(r, 20, 20)
elif self._type == QtGui.QRegion.Ellipse:
painter.drawEllipse(self._rect)
path.addEllipse(r)
stroker = QtGui.QPainterPathStroker()
stroker.setWidth(s.width())
stroke_path = stroker.createStroke(path)
# painter.setPen(QtCore.Qt.NoPen)
painter.setBrush(QtGui.QBrush(QtCore.Qt.cyan, QtCore.Qt.SolidPattern))
painter.drawPath(stroke_path)
I would like to draw some lines with QPainter, then move the start (x1,y1) coordinates of lines to centerpoint and some other lines which want to offset from center. Those lines should behave programmatically based on value of ellipse or other values. I have tried myself different ways to come around it but does not work.
To QRect can utilize codes such as
moveCenter, moveTopLeft, etc...
But for Qline there are not such methods. According to PyQt doc, a line can be drawn by this:
QLine(int x1, int y1, int x2, int y2)
QLine(const QPoint &p1, const QPoint &p2)
Maybe this line should be used in order to offset it. But no knowlegde to do it.
translated(const QPoint &offset)
On another hand would like to draw some texts and offset them in similar way as Qline.
Look at figures below to see what is that I exactly want to do?
Visualisation
What I have achieved so far.
What I want to achieve.
The code:
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
class Foo(QtWidgets.QWidget):
def __init__(self, parent=None):
super(Foo, self).__init__(parent)
self.setGeometry(QtCore.QRect(200, 100, 700, 600))
self.paint = Paint()
self.sizeHint()
self.lay = QtWidgets.QVBoxLayout()
self.lay.addWidget(self.paint)
self.setLayout(self.lay)
class Paint(QtWidgets.QWidget):
def __init__(self, parent=None):
super(Paint, self).__init__(parent)
self.setBackgroundRole(QtGui.QPalette.Base)
self.setAutoFillBackground(True)
xl = self.rect().center().x()
yl = self.rect().center().y()
self.e = QtCore.QRect(QtCore.QPoint(), QtCore.QSize(250, 250))
self.l = QtCore.QLine(QtCore.QPoint(xl, yl) , QtCore.QPoint(self.width(), self.height()/2))
def paintEvent(self, event):
pen = QtGui.QPen()
brush = QtGui.QBrush( QtCore.Qt.darkCyan, QtCore.Qt.Dense7Pattern)
painter = QtGui.QPainter(self)
painter.setBrush(brush)
painter.setPen(pen)
painter.setRenderHint(QtGui.QPainter.Antialiasing)
self.e.moveCenter(self.rect().center())
painter.drawEllipse(self.e)
painter.drawLine(self.l)
# painter.drawText('D')
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
w = Foo()
w.show()
sys.exit(app.exec_())
The Update issue:
I have updated the code, I manage to draw what I want. But having another challenge. You could see on figure below.
When code runs and displays
When Widget minimizes or maximizes, some lines disappears?
The Update code:
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
class Foo(QtWidgets.QWidget):
def __init__(self, parent=None):
super(Foo, self).__init__(parent)
self.setGeometry(QtCore.QRect(200, 100, 700, 600))
self.paint = Paint()
self.sizeHint()
self.lay = QtWidgets.QVBoxLayout()
self.lay.addWidget(self.paint)
self.setLayout(self.lay)
class Paint(QtWidgets.QWidget):
def __init__(self, parent=None):
super(Paint, self).__init__(parent)
self.setBackgroundRole(QtGui.QPalette.Base)
self.setAutoFillBackground(True)
self.e = QtCore.QRect(QtCore.QPoint(), QtCore.QSize(250, 250))
self.l1 = QtCore.QLine(QtCore.QPoint(), QtCore.QPoint(200, 0))
self.l2 = QtCore.QLine(QtCore.QPoint(), QtCore.QPoint(0, -200))
self.vl = QtCore.QLine(QtCore.QPoint(), QtCore.QPoint(0, -125))
delta = QtCore.QPoint(20, 0)
self.hl = QtCore.QLine(-delta, self.e.topRight() + delta)
self.al = QtCore.QLine(QtCore.QPoint(), QtCore.QPoint(-20, -20))
self.a2 = QtCore.QLine(QtCore.QPoint(), QtCore.QPoint(-20, 20))
self.a3 = QtCore.QLine(QtCore.QPoint(), QtCore.QPoint(20, 20))
self.a4 = QtCore.QLine(QtCore.QPoint(), QtCore.QPoint(-20, 20))
self._factor = 1.0
def paintEvent(self, event):
pen = QtGui.QPen()
brush = QtGui.QBrush( QtCore.Qt.darkCyan, QtCore.Qt.Dense7Pattern)
painter = QtGui.QPainter(self)
painter.setBrush(brush)
painter.setPen(pen)
painter.setRenderHint(QtGui.QPainter.Antialiasing)
self.e.moveCenter(self.rect().center())
self.l1.translate(self.rect().center() - self.l1.p1())
self.l2.translate(self.rect().center() - self.l2.p1())
self.al.translate(self.l1.p2())
self.a2.translate(self.l1.p2())
painter.translate(self.rect().center())
painter.scale(self._factor, self._factor)
painter.translate(-self.rect().center())
painter.drawEllipse(self.e)
painter.drawLine(self.l1)
painter.drawLine(self.l2)
fnt = painter.font()
fnt.setPointSize(20)
painter.setFont(fnt)
h = QtGui.QFontMetrics(painter.font()).height()
p = QtCore.QPoint(self.rect().center().x(), self.e.top() - 3*h)
u = QtCore.QPoint(self.e.right() + 3*h, self.rect().center().y())
painter.drawText(p, "y")
painter.drawText(u, "x")
r = QtCore.QRect(QtCore.QPoint(self.e.x(), self.e.bottom()), QtCore.QSize(self.e.width(), h))
painter.drawText(r, QtCore.Qt.AlignCenter, "D = 350mm")
offset = QtCore.QPoint(0, 1.5*h)
self.vl.translate(self.e.bottomLeft() - self.vl.p1() + offset)
painter.drawLine(self.vl)
self.vl.translate(self.e.width(), 0)
painter.drawLine(self.vl)
self.hl.translate(self.e.bottomLeft() + offset - QtCore.QPoint(0, 0.4*h))
self.a3.translate(self.l2.p2())
self.a4.translate(self.l2.p2())
painter.drawLine(self.hl)
painter.drawLine(self.al)
painter.drawLine(self.a2)
painter.drawLine(self.a3)
painter.drawLine(self.a4)
def wheelEvent(self, event):
self._factor *= 1.01**(event.angleDelta().y()/15.0)
self.update()
super(Paint, self).wheelEvent(event)
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
w = Foo()
w.show()
sys.exit(app.exec_())
I do not know why it behaves like this? any comment or help I appreciate much.
Qt does not know what size the widget will have at the beginning so self.rect() will have any size, for example in my test self.rect() in __init__ returns PyQt5.QtCore.QRect(0, 0, 640, 480) but in paintEvent() it returns PyQt5.QtCore.QRect(0, 0, 678, 578) so that's why the calculation is incorrect.
the solution is to move the line with translate()(do not use translated() because this creates a new QLine and that's what I do not want)
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
class Foo(QtWidgets.QWidget):
def __init__(self, parent=None):
super(Foo, self).__init__(parent)
self.setGeometry(QtCore.QRect(200, 100, 700, 600))
self.paint = Paint()
self.sizeHint()
self.lay = QtWidgets.QVBoxLayout()
self.lay.addWidget(self.paint)
self.setLayout(self.lay)
class Paint(QtWidgets.QWidget):
def __init__(self, parent=None):
super(Paint, self).__init__(parent)
self.setBackgroundRole(QtGui.QPalette.Base)
self.setAutoFillBackground(True)
self.e = QtCore.QRect(QtCore.QPoint(), QtCore.QSize(250, 250))
self.l1 = QtCore.QLine(QtCore.QPoint(), QtCore.QPoint(200, 0))
self.l2 = QtCore.QLine(QtCore.QPoint(), QtCore.QPoint(0, -200))
def paintEvent(self, event):
pen = QtGui.QPen()
brush = QtGui.QBrush( QtCore.Qt.darkCyan, QtCore.Qt.Dense7Pattern)
painter = QtGui.QPainter(self)
painter.setBrush(brush)
painter.setPen(pen)
painter.setRenderHint(QtGui.QPainter.Antialiasing)
self.e.moveCenter(self.rect().center())
self.l1.translate(self.rect().center() - self.l1.p1())
self.l2.translate(self.rect().center() - self.l2.p1())
painter.drawEllipse(self.e)
painter.drawLine(self.l1)
painter.drawLine(self.l2)
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
w = Foo()
w.show()
sys.exit(app.exec_())
Update:
class Paint(QtWidgets.QWidget):
def __init__(self, parent=None):
super(Paint, self).__init__(parent)
self.setBackgroundRole(QtGui.QPalette.Base)
self.setAutoFillBackground(True)
self.e = QtCore.QRect(QtCore.QPoint(), QtCore.QSize(250, 250))
self.l1 = QtCore.QLine(QtCore.QPoint(), QtCore.QPoint(200, 0))
self.l2 = QtCore.QLine(QtCore.QPoint(), QtCore.QPoint(0, -200))
self.vl = QtCore.QLine(QtCore.QPoint(), QtCore.QPoint(0, -125))
delta = QtCore.QPoint(20, 0)
self.hl = QtCore.QLine(-delta, self.e.topRight() + delta)
def paintEvent(self, event):
pen = QtGui.QPen()
brush = QtGui.QBrush( QtCore.Qt.darkCyan, QtCore.Qt.Dense7Pattern)
painter = QtGui.QPainter(self)
painter.setBrush(brush)
painter.setPen(pen)
painter.setRenderHint(QtGui.QPainter.Antialiasing)
self.e.moveCenter(self.rect().center())
self.l1.translate(self.rect().center() - self.l1.p1())
self.l2.translate(self.rect().center() - self.l2.p1())
painter.drawEllipse(self.e)
painter.drawLine(self.l1)
painter.drawLine(self.l2)
fnt = painter.font()
fnt.setPointSize(25)
painter.setFont(fnt)
h = QtGui.QFontMetrics(painter.font()).height()
p = QtCore.QPoint(self.rect().center().x(), self.e.bottom() + 0.8*h)
r = QtCore.QRect(QtCore.QPoint(self.e.x(), self.e.bottom()), QtCore.QSize(self.e.width(), h))
painter.drawText(r, QtCore.Qt.AlignCenter, "D")
offset = QtCore.QPoint(0, 1.5*h)
self.vl.translate(self.e.bottomLeft() - self.vl.p1() + offset)
painter.drawLine(self.vl)
self.vl.translate(self.e.width(), 0)
painter.drawLine(self.vl)
self.hl.translate(self.e.bottomLeft() + offset - QtCore.QPoint(0, 20))
painter.drawLine(self.hl)