Using PyQt5 I am viewing an image in a QGraphicsView. I want to be able to zoom in/out while pressing ctrl and using the mouse wheel. I have this working, however if the image is too large, and there are scroll bars, it ignores the zoom functionality until you scroll to the top or bottom.
How can I fix this to where it does not scroll when ctrl is pressed, while allowing it to zoom in/out.
from PyQt5.QtWidgets import QFileDialog, QLineEdit, QWidget, QPushButton, QApplication, QVBoxLayout, QLabel, QGraphicsView, QGraphicsPixmapItem, QGraphicsScene
from PyQt5.QtCore import pyqtSignal, Qt
from pdf2image import convert_from_path
from PIL import ImageQt
import sys
class step1(QWidget):
changeViewSignal = pyqtSignal()
def __init__(self, parent=None):
super(step1, self).__init__(parent)
self.name = QLineEdit(self)
self.fileBtn = QPushButton("Select file", self)
self.nextBtn = QPushButton("Next", self)
self.graphicsView = QGraphicsView()
# self.graphicsView.setFrameShadow(QFrame.Raised)
# self.graphicsView.setSizeAdjustPolicy(QAbstractScrollArea.AdjustToContentsOnFirstShow)
self.graphicsView.setHorizontalScrollBarPolicy()
self.layout = QVBoxLayout(self)
self.layout.addWidget(self.name)
self.layout.addWidget(self.fileBtn)
self.layout.addWidget(self.nextBtn)
self.layout.addWidget(self.graphicsView)
self.fileBtn.clicked.connect(self.convert_file)
def wheelEvent(self, event):
modifiers = QApplication.keyboardModifiers()
if modifiers == Qt.ControlModifier:
self.graphicsView.scrollContentsBy(0,0)
x = event.angleDelta().y() / 120
if x > 0:
self.graphicsView.scale(1.05, 1.05)
elif x < 0:
self.graphicsView.scale(.95, .95)
def convert_file(self):
fname = QFileDialog.getOpenFileName(self, 'Open File', 'c:\\', "PDF Files (*.pdf)")
if len(fname[0]) > 0:
pages = convert_from_path(fname[0])
images = []
qimage = ImageQt.toqpixmap(pages[0])
item = QGraphicsPixmapItem(qimage)
scene = QGraphicsScene(self)
scene.addItem(item)
self.graphicsView.setScene(scene)
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = step1()
ex.show()
sys.exit(app.exec_())
The scrolling is first handled by the QGraphicsView before it would be propagated up to the parent widget where you are reimplementing the wheelEvent. This is why the scrolling occurs according to the normal QGraphicsView behavior when it has space to scroll.
A solution is to subclass QGraphicsView and reimplement the wheelEvent there instead.
class GraphicsView(QGraphicsView):
def wheelEvent(self, event):
if event.modifiers() & Qt.ControlModifier:
x = event.angleDelta().y() / 120
if x > 0:
self.scale(1.05, 1.05)
elif x < 0:
self.scale(.95, .95)
else:
super().wheelEvent(event)
Then use the subclass name here:
self.graphicsView = GraphicsView()
Besides the proper solution proposed by alec, there's also the option of using an event filter, which can be useful for UIs created in Designer without the need of using promoted widgets.
The important aspect to keep in mind is that the event filter must be installed on the view's viewport() (the widget in which the contents of the scene are actually rendered and, possibly, scrolled), because that is the widget that will receive the wheel event: input events are always sent to the widget under the mouse (or has keyboard focus)[1], and possibly propagated to their parents if the event is not handled[2].
class step1(QWidget):
def __init__(self, parent=None):
# ...
self.graphicsView.viewport().installEventFilter(self)
def eventFilter(self, source, event):
if event.type() == event.Wheel and event.modifiers() & Qt.ControlModifier:
x = event.angleDelta().y() / 120
if x > 0:
self.graphicsView.scale(1.05, 1.05)
elif x < 0:
self.graphicsView.scale(.95, .95)
return True
return super().eventFilter(source, event)
Returning True means that the viewport has handled the event, and it should not be propagated to the parent; QGraphicsView is based on QAbstractScrollArea, and if a wheel event is not handled by the viewport it will call the base wheelEvent implementation of the viewport's parent (the graphics view), which by default will post the event to the scroll bars. If the filter returns True, it will avoid that propagation, thus preventing scrolling.
Note that you should not use scrollContentsBy unless you really know what you're doing; as the documentation explains: «Calling this function in order to scroll programmatically is an error, use the scroll bars instead».
[1] Mouse events are always sent to the topmost widget under the mouse, unless a modal child window is active, or there is a mouse grabber, which is a widget that has received a mouse button press event but didn't receive a mouse button release event yet, or a widget on which grabMouse() was explicitly called. Keyboard events are always sent to the widget of the active window that has current focus, or the widget on which grabKeyboard() has been explicitly called.
[2] "handled event" can be a confusing concept: it doesn't mean that the widget actually "does" something with the event, nor that it doesn't, no matter if the event then becomes accepted or ignored. A widget could "ignore" an event and still react to it in some way: for instance, you might need to notify the user that the event has been received, but let the parent manage it anyway.
Related
I have a small GUI app made using pyqt5.
I found a strange problem while using eventFilter...
def eventFilter(self, source, event):
if event.type() == QtCore.QEvent.KeyPress:
# RETURN
if event.key() == QtCore.Qt.Key_Return:
if source is self.userLineEdit:
self.pswLineEdit.setFocus()
elif source is self.pswLineEdit:
self.LoginButton.click()
# TAB
elif event.key() == QtCore.Qt.Key_Tab:
if source is self.userLineEdit:
self.pswLineEdit.setFocus()
return super().eventFilter(source, event)
While pressing enter key just behave normally, tab key does not.
I don't know where the problem could be. I'm going to link a video to show the exact problem as I'm not able to describe how this is not working
Link to video
I know it's pixelated (sorry) but the important thing is the behavior of the cursor
SMALL EXAMPLE
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QLineEdit
from PyQt5 import QtCore
class App(QWidget):
def __init__(self):
super().__init__()
self.title = 'Hello, world!'
self.left = 10
self.top = 10
self.width = 640
self.height = 480
self.initUI()
def initUI(self):
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)
self.userEdit = QLineEdit(self)
self.pswEdit = QLineEdit(self)
self.userEdit.setPlaceholderText("Username")
self.pswEdit.setPlaceholderText("Password")
self.userEdit.installEventFilter(self)
self.pswEdit.installEventFilter(self)
mainLayout = QVBoxLayout()
mainLayout.addWidget(self.userEdit)
mainLayout.addWidget(self.pswEdit)
self.setLayout(mainLayout)
self.show()
def eventFilter(self, source, event):
if event.type() == QtCore.QEvent.KeyPress:
# RETURN
if event.key() == QtCore.Qt.Key_Return:
if source is self.userEdit:
self.pswEdit.setFocus()
# TAB
elif event.key() == QtCore.Qt.Key_Tab:
if source is self.userEdit:
self.pswEdit.setFocus()
return super().eventFilter(source, event)
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = App()
sys.exit(app.exec_())
If you don't filter events, they are processed by the object and eventually propagated back to the parent.
By default, QWidget will try to focus the next (or previous, for Shift+Tab) child widget in the focus chain, by calling its focusNextPrevChild(). If it can do it, it will actually set the focus on that widget, otherwise the event is ignored and propagated to the parent.
Since most widgets (including QLineEdit) don't handle the tab keys for focus changes on their own, as they don't have children, their parent will receive it, which will call focusNextPrevChild() looking for another child widget, and so on, up to the object tree, until a widget finally can handle the key, eventually changing the focus.
In your case, this is what's happening:
you check events and find that the tab key event is received by the first line edit;
you set the focus on the other line edit, the password field;
you let the event be handled anyway by the widget, since you're not ignoring or filtering it out;
the first line edit calls focusNextPrevChild() but is not able to do anything with it;
the event is propagated to the parent, which then calls its own focusNextPrevChild();
the function checks the current focused child widget, which is the password field you just focused, and finds the next, which coincidentally is the first line edit, which gets focused again;
The simple solution is to just add return True after changing the focus, so that the event doesn't get propagated to the parent causing a further focus change:
if event.key() == QtCore.Qt.Key_Tab:
if source is self.userEdit:
self.pswEdit.setFocus()
return True
Note that overriding the focus behavior is quite complex, and you have to be very careful about how focus and events are handled, especially for specific widgets that might deal with events in particular ways (studying the Qt sources is quite useful for this), otherwise you'll get unexpected behavior or even fatal recursion.
For instance, there's normally no need for an event filter for the return key, as QLineEdit already provides the returnPressed signal:
self.userEdit.returnPressed.connect(self.pswEdit.setFocus)
Qt already has a quite thorough focus management system, if you just want more control over the way the tab chain works use existing functions like setTabOrder() on the parent or top level window, and if you want to have more control over how (or if) they get it, use setFocusPolicy().
I have a context menu with a checkbox and a spinbox. Both work as expected, except that when I am typing a number in the spinbox, I tend to hit enter to close the menu, but that also toggles the checkbox. Does anyone know how to prevent that?
minimal example:
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QFrame, QMenu, QAction, QWidgetAction, QFormLayout, QSpinBox
from PyQt5.QtCore import Qt
t = True
v = 0
class SpinAction(QWidgetAction):
def __init__(self, parent):
super(SpinAction, self).__init__(parent)
w = QWidget()
layout = QFormLayout(w)
self.spin = QSpinBox()
layout.addRow('value', self.spin)
w.setLayout(layout)
self.setDefaultWidget(w)
def _menu(position):
menu = QMenu()
test_action = QAction(text="Test", parent=menu, checkable=True)
test_action.setChecked(t)
test_action.toggled.connect(toggle_test)
spin_action = SpinAction(menu)
spin_action.spin.setValue(v)
spin_action.spin.valueChanged.connect(spin_changed)
menu.addAction(test_action)
menu.addAction(spin_action)
action = menu.exec_(w.mapToGlobal(position))
def toggle_test(val):
global t
t = val
def spin_changed(val):
global v
v = val
app = QApplication(sys.argv)
w = QFrame()
w.setContextMenuPolicy(Qt.CustomContextMenu)
w.customContextMenuRequested.connect(_menu)
w.show()
sys.exit(app.exec_())
The widget must accept focus, so a proper focus policy (StrongFocus or WheelFocus) must be set, but since it's a container you should also set the focus proxy to the spin, so that it will handle the focus for it.
In this way the keyboard navigation of the menu will also work properly by using arrows or Tab to focus the spinbox.
The action also has to be set as the active action of the menu in order to prevent the menu to accept events that may trigger other actions, and a way to achieve that is to install an event filter on the spin and check for events that should make the widget action as the active one, like FocusIn and Enter event.
Note that this results in some unintuitive results from the UX perspective: by default, hovering a normal QAction makes it the active one, but the user might want to move the mouse away from the spinbox in order to edit it without having the mouse on it, and by doing it another action could become active; in the meantime the spin should still keep the focus for obvious reasons. The result is that the other action might seem visually selected while the spinbox has focus. There is no obvious solution for this, and that's why widgets used for QWidgetActions should always be chosen with care.
class SpinAction(QWidgetAction):
FocusEvents = QtCore.QEvent.FocusIn, QtCore.QEvent.Enter
ActivateEvents = QtCore.QEvent.KeyPress, QtCore.QEvent.Wheel)
WatchedEvents = FocusEvents + ActivateEvents
def __init__(self, parent):
# ...
w.setFocusPolicy(self.spin.focusPolicy())
w.setFocusProxy(self.spin)
self.spin.installEventFilter(self)
def eventFilter(self, obj, event):
if obj == self.spin and event.type() in self.WatchedEvents:
if isinstance(self.parent(), QtWidgets.QMenu):
self.parent().setActiveAction(self)
if event.type() in self.FocusEvents:
self.spin.setFocus()
return super().eventFilter(obj, event)
Note: the obj == self.spin condition is required since QWidgetAction already installs an event filter. A more elegant solution is to create a QObject subclass intended for that purpose only, and only overriding eventFilter().
I have a QMainWindow application that has multiple widgets (buttons, labels, etc.) inside it.
How can I get an event when the user presses ANYWHERE of the app?
I tried to customize mousePressEvent() function, but this doesn't accept the event when other widgets (buttons, labels, etc.) are pressed.
Explanation:
The handling of mouse events between the widgets goes from children to parents, that is, if the child does not accept the event (it does not use it) then it will pass the event to the parent. For example, if you press on the QPushButton, it accepts the event and the parent is not notified, unlike QLabel that does not consume it, so the event passes to the parent.
Tools:
On the other hand, there are several methods to listen to events in general, such as:
Override any method like mousePressEvent, keyPressEvent, etc or the event or customEvent method.
Use an eventFilter.
Solution:
An alternative is to apply some previous method to all the widgets but you can discard all of them for the current objective, for example:
In the first and second method it would involve detecting when a widget is added or removed (using QEvent::ChildAdded or QEvent::ChildRemoved).
In the first method it would imply override the methods that many times is impossible.
With the above, the problem is attacked on the widgets side, but there are other alternatives:
Override the notify() method of Q{Core, GUi,}Application, verify that it is a widget and that it belongs to the window, it also implies discriminating if the event has already been consumed.
Listen to the mouse event associated with the window (QWindow).
In this case the most reasonable is the second method.
import sys
from PyQt5 import QtCore, QtWidgets
class MouseObserver(QtCore.QObject):
pressed = QtCore.pyqtSignal(QtCore.QPoint)
released = QtCore.pyqtSignal(QtCore.QPoint)
moved = QtCore.pyqtSignal(QtCore.QPoint)
def __init__(self, window):
super().__init__(window)
self._window = window
self.window.installEventFilter(self)
#property
def window(self):
return self._window
def eventFilter(self, obj, event):
if self.window is obj:
if event.type() == QtCore.QEvent.MouseButtonPress:
self.pressed.emit(event.pos())
elif event.type() == QtCore.QEvent.MouseMove:
self.moved.emit(event.pos())
elif event.type() == QtCore.QEvent.MouseButtonRelease:
self.released.emit(event.pos())
return super().eventFilter(obj, event)
class MainWindow(QtWidgets.QMainWindow):
pass
def main(args):
app = QtWidgets.QApplication(args)
w = MainWindow()
w.show()
mouse_observer = MouseObserver(w.window().windowHandle())
mouse_observer.pressed.connect(lambda pos: print(f"pressed: {pos}"))
mouse_observer.released.connect(lambda pos: print(f"released: {pos}"))
mouse_observer.moved.connect(lambda pos: print(f"moved: {pos}"))
app.exec_()
if __name__ == "__main__":
main(sys.argv)
I created a small GUI that allows me to draw a number. That number is supposed to be classified with a CNN. The CNN is not connected to this GUI yet. Will do that later on. I am still very new to PyQt5 and used some code that i found online for the drawing with QImage. It works, but at the moment i can draw all over the GUI. Is it possible to place that in a widget? So that I can only draw inside a specific frame and not all over the GUI?
So basically how can i get the self.image = QImage(...) iside a widget or something that i created earlier on my GUI? Is that possible somehow or would you even suggest to solve it in totaly different way?
import sys
from PyQt5 import QtWidgets
from PyQt5.QtGui import QIcon, QImage, QPainter, QPen, QBrush
from PyQt5.QtCore import Qt, QPoint
from UI.mainwindow_2 import Ui_MainWindow
import matplotlib.pyplot as plt
import numpy as np
class MainWindow(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super().__init__(parent)
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
self.image = QImage(self.size(), QImage.Format_RGB32)
self.image.fill(Qt.white)
self.drawing = False
self.brushSize = 28
self.brushColor = Qt.black
self.lastPoint = QPoint()
self.ui.Clear.clicked.connect(self.clear)
def mousePressEvent(self, event):
if event.button() == Qt.LeftButton:
self.drawing = True
self.lastPoint = event.pos()
def mouseMoveEvent(self, event):
if(event.buttons() & Qt.LeftButton) & self.drawing:
painter = QPainter(self.image)
painter.setPen(QPen(self.brushColor, self.brushSize, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin))
painter.drawLine(self.lastPoint, event.pos())
self.lastPoint = event.pos()
self.update()
def mouseReleaseEvent(self, event):
if event.button() == Qt.LeftButton:
self.drawing = False
def paintEvent(self, event):
canvasPainter = QPainter(self)
canvasPainter.drawImage(self.rect(),self.image, self.image.rect())
def clear(self):
self.image.fill(Qt.white)
self.update()
def main():
app = QtWidgets.QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec())
if __name__ == "__main__":
main()
First of all, the following aspects must be considered:
paint events are received by any (visible) QWidget subclass
painting is always constricted to the geometry of the widget
painting always happens from the bottom to the top, so whenever a widget has some children, whatever has been painted on that parent widget will be potentially covered by those children
So, the first thing to do is to implement the paintEvent only on the actual widget for which you want to paint. Since you're using Designer, this makes things a bit more complex, as there is no way to subclass a widget that already exists in an ui.
Luckily, Qt has a concept called "promoted widgets": it allows to "expand" a certain widget by specifying the custom subclass that will be actually used when the ui will be finally generated in the program.
choose which widget in your ui will be used for painting; I suggest you to start from a basic QWidget, I'll explain more about this later;
right click on it, and select "Promote to..." from the context menu;
in the "Promoted class name" type the exact class name you are going to use (let's say "Canvas");
in the "Header file" field, type the file name that will contain that class, as it would appear in an import statement (meaning that it should not have the py extension!); assuming you want to do everything in a single script and your script is named "mycanvas.py", type "mycanvas" in that field;
ensure that the "Base class name" combo is set to the exact class type of the widget you've chosen (QWidget, in this case, which is usually automatically selected)
click "Add" and then "Promote";
save the ui and generate the file with pyuic;
Now, the implementation of your mycanvas.py file is simple:
class Canvas(QtWidgets.QWidget):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.image = QImage(self.size(), QImage.Format_RGB32)
self.image.fill(Qt.white)
self.drawing = False
self.brushSize = 28
self.brushColor = Qt.black
self.lastPoint = QPoint()
# ... all the painting related methods, as you did in your code
class MainWindow(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super().__init__(parent)
self.ui.Clear.clicked.connect(self.ui.canvas.clear)
def main():
# ...
Two considerations:
a QFrame usually has some borders, and since painting can always happen within the whole widget size, you might end up painting on the borders too. If you want a QFrame and paint inside that widget, then add a QWidget as a child to that frame and ensure that a layout is set for the frame;
setting the QImage size within the init is not a good approach, as the widget might change its size or it could be initialized with a size smaller than it will eventually have; you either set a fixed size in the __init__ before creating the QImage, or you keep track of the points/lines in an internal container and continuously draw the contents in the paintEvent;
So I'm relatively new to qt and fairly seasoned with python.
However, I have an instance where I want multiple widgets (in this case labels) to share the same custom context menu but I need to get access to the widget's information.
When I use setContextMenuPolicy and customContextMenuRequested.connect on each label I only get information for the first label despite accessing the context menu with the second label.
Below is a stripped down version of what I'm working with:
from PyQt5 import QtGui
from PyQt5 import QtCore
from PyQt5.QtWidgets import QApplication, QMainWindow, QMenu, QLabel
import sys
class Window(QMainWindow):
def __init__(self):
super().__init__()
self.title = "PyQt5 Context Menu"
self.top = 200
self.left = 500
self.width = 200
self.height = 100
self.InitWindow()
def InitWindow(self):
self.setWindowIcon(QtGui.QIcon("icon.png"))
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)
self.firstLabel = QLabel(self)
self.firstLabel.setText("Meep!")
self.firstLabel.setObjectName("firstLabel")
self.firstLabel.setStyleSheet("background-color: rgb(252, 233, 79);")
self.firstLabel.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
self.firstLabel.customContextMenuRequested.connect(self.customMenuEvent)
self.firstLabel.setGeometry(QtCore.QRect(0,0,50,30))
self.secondLabel = QLabel(self)
self.secondLabel.setText("Peem!")
self.secondLabel.setObjectName("secondLabel")
self.secondLabel.setStyleSheet("background-color: rgb(79,233, 252);")
self.secondLabel.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
self.secondLabel.customContextMenuRequested.connect(self.customMenuEvent)
self.secondLabel.setGeometry(QtCore.QRect(80,40,50,30))
print("FIRST:", self.firstLabel)
print("SECOND:", self.secondLabel)
self.show()
def customMenuEvent(self, eventPosition):
child = self.childAt(eventPosition)
print(child)
contextMenu = QMenu(self)
getText = contextMenu.addAction("Text")
getName = contextMenu.addAction("Name")
quitAct = contextMenu.addAction("Quit")
action = contextMenu.exec_(self.mapToGlobal(eventPosition))
if action == getText:
print(child.text())
if action == getName:
print(child.objectName())
if action == quitAct:
self.close()
App = QApplication(sys.argv)
window = Window()
sys.exit(App.exec())
From the documentation about the customContextMenuRequested(pos) signal:
The position pos is the position of the context menu event that the widget receives
This means that you will always receive the mouse position relative to the widget that fires the signal.
You're using QWidget.childAt(), which is relative to the parent geometry, but since the provided position is relative to the child widget, you'll always end up with coordinates that are relative to the top left corner of the parent.
This becomes clear if you try to set the geometry of the first widget in a position that's not the top left corner: even if you right-click on the first widget, you'll see that the menu will not appear where you clicked. If you look closely, you'll also see that the menu appears exactly at the position you clicked, based on the coordinates of the parent top left corner.
For the sake of simplicity, an easy solution would be to map the coordinates from the "sender" (which is the object that fired the last signal the receiver has received) to its parent:
def customMenuEvent(self, eventPosition):
child = self.childAt(self.sender().mapTo(self, eventPosition))
contextMenu = QMenu(self)
getText = contextMenu.addAction("Text")
getName = contextMenu.addAction("Name")
quitAct = contextMenu.addAction("Quit")
# note that the mapToGlobal is referred to the child!
action = contextMenu.exec_(child.mapToGlobal(eventPosition))
# ...
But be aware that this could lead to some inconsistency, especially when dealing with multithreading (as, theoretically, another thread could have fired another signal between the right click event and the moment the receiver actually receives it).
There are various different approaches to avoid that, but IT mostly depends on how you are going to structure your program.
For example, you could use a lambda to add an argument that helps to identify the source from which the event has been sent:
self.firstLabel.customContextMenuRequested.connect(
lambda pos, child=self.firstLabel: self.customMenuEvent(pos, child))
# ...
def customMenuEvent(self, eventPosition, child):
# ...