How to make QSlider unclickable - python

I'm creating a GUI where I have a few sliders. I want each QSlider such that it can only be dragged. Sometimes, if I click on any part of a QSlider, the position of the slider changes. How can I stop that from happening?

The solution is to verify that when you do not press with the mouse in the slider groove:
from PyQt5 import QtCore, QtWidgets
class SliderUnclickable(QtWidgets.QSlider):
def mousePressEvent(self, event):
opt = QtWidgets.QStyleOptionSlider()
self.initStyleOption(opt)
pressedControl = self.style().hitTestComplexControl(QtWidgets.QStyle.CC_Slider, opt, event.pos(), self)
if pressedControl != QtWidgets.QStyle.SC_SliderGroove:
super(SliderUnclickable, self).mousePressEvent(event)
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
w = QtWidgets.QWidget()
flay = QtWidgets.QFormLayout(w)
w1 = QtWidgets.QSlider(QtCore.Qt.Horizontal)
w2 = SliderUnclickable(QtCore.Qt.Horizontal)
flay.addRow("default QSlider: ", w1)
flay.addRow("SliderUnclickable: ", w2)
w.show()
sys.exit(app.exec_())

Related

PyQt6 Isn't calling any events for hovering over a frame

My goal is to detect when a user hovers or stops hovering over a frame, but whenever I try to detect that with an eventFilter, there are just no events that get run that show that. The event IDs for hoverEnter, hoverLeave, and hoverMouseMove are 127, 128, and 129, but if you run the code, you'll see that they just don't come up. Here is the code that fails:
import sys
from PyQt6.QtCore import *
from PyQt6.QtGui import *
from PyQt6.QtWidgets import *
class MainApp(QWidget):
def __init__(self):
super().__init__()
self.setWindowTitle("Test Window")
self.resize(300, 200)
self.outerLayout = QHBoxLayout()
self.outerLayout.setContentsMargins(50, 50, 50, 50)
self.frame = QFrame()
self.frame.setStyleSheet("background-color: lightblue;")
self.innerLayout = QHBoxLayout(self.frame)
self.label = QLabel(self.frame)
self.label.setText("Example Frame")
self.innerLayout.addWidget(self.label)
self.outerLayout.addWidget(self.frame)
self.setLayout(self.outerLayout)
def eventFilter(self, obj, event):
if event.type() == 127:
print("hovered")
elif event.type() == 128:
print("no longer hovered")
elif event.type() == 129:
print("hover move event")
print(event.type())
return True
if __name__ == "__main__":
app = QApplication(sys.argv)
window = MainApp()
window.installEventFilter(window)
window.show()
sys.exit(app.exec())
My end goal here is to be able to detect when a QFrame is clicked. I was thinking I would try to do that by checking for mouse clicks, and if the mouse is hovering over the frame, trigger the function.
First of all it should be noted that clicked is not an event but a signal. The button clicked signal is emitted when the button receives the MouseButtonRelease event.
In this answer I will show at least the following methods to implement the clicked signal in the QFrame.
Override mouseReleaseEvent
import sys
from PyQt6.QtCore import pyqtSignal, pyqtSlot
from PyQt6.QtWidgets import QApplication, QFrame, QHBoxLayout, QLabel, QWidget
class Frame(QFrame):
clicked = pyqtSignal()
def mouseReleaseEvent(self, event):
super().mouseReleaseEvent(event)
self.clicked.emit()
class MainApp(QWidget):
def __init__(self):
super().__init__()
self.setWindowTitle("Test Window")
self.resize(300, 200)
self.outerLayout = QHBoxLayout(self)
self.outerLayout.setContentsMargins(50, 50, 50, 50)
self.frame = Frame()
self.frame.setStyleSheet("background-color: lightblue;")
self.label = QLabel(text="Example Frame")
self.innerLayout = QHBoxLayout(self.frame)
self.innerLayout.addWidget(self.label)
self.outerLayout.addWidget(self.frame)
self.frame.clicked.connect(self.handle_clicked)
#pyqtSlot()
def handle_clicked(self):
print("frame clicked")
if __name__ == "__main__":
app = QApplication(sys.argv)
window = MainApp()
window.show()
sys.exit(app.exec())
Use a eventFilter:
import sys
from PyQt6.QtCore import QEvent
from PyQt6.QtWidgets import QApplication, QFrame, QHBoxLayout, QLabel, QWidget
class MainApp(QWidget):
def __init__(self):
super().__init__()
self.setWindowTitle("Test Window")
self.resize(300, 200)
self.outerLayout = QHBoxLayout(self)
self.outerLayout.setContentsMargins(50, 50, 50, 50)
self.frame = QFrame()
self.frame.setStyleSheet("background-color: lightblue;")
self.label = QLabel(text="Example Frame")
self.innerLayout = QHBoxLayout(self.frame)
self.innerLayout.addWidget(self.label)
self.outerLayout.addWidget(self.frame)
self.frame.installEventFilter(self)
# for move mouse
# self.frame.setMouseTracking(True)
def eventFilter(self, obj, event):
if obj is self.frame:
if event.type() == QEvent.Type.MouseButtonPress:
print("press")
# for move mouse
# elif event.type() == QEvent.Type.MouseMove:
# print("move")
elif event.type() == QEvent.Type.MouseButtonRelease:
print("released")
return super().eventFilter(obj, event)
if __name__ == "__main__":
app = QApplication(sys.argv)
window = MainApp()
window.show()
sys.exit(app.exec())
Plus
A big part of the error of the O attempt is that by doing window.installEventFilter(window) it is only listening for events from the window itself and not from the QFrame. The solution is to send the QFrame events to the class window.frame.installEventFilter(window).
On the other hand, do not use numerical codes but the enumerations since they are more readable.
On the other hand, for the mouse event, the Qt::WA_Hover attribute must be enabled(Read the docs for more information)
import sys
from PyQt6.QtCore import QEvent, Qt
from PyQt6.QtWidgets import QApplication, QFrame, QHBoxLayout, QLabel, QWidget
class MainApp(QWidget):
def __init__(self):
super().__init__()
self.setWindowTitle("Test Window")
self.resize(300, 200)
self.outerLayout = QHBoxLayout(self)
self.outerLayout.setContentsMargins(50, 50, 50, 50)
self.frame = QFrame()
self.frame.setStyleSheet("background-color: lightblue;")
self.label = QLabel(text="Example Frame")
self.innerLayout = QHBoxLayout(self.frame)
self.innerLayout.addWidget(self.label)
self.outerLayout.addWidget(self.frame)
self.frame.setAttribute(Qt.WidgetAttribute.WA_Hover)
self.frame.installEventFilter(self)
def eventFilter(self, obj, event):
if obj is self.frame:
if event.type() == QEvent.Type.HoverEnter:
print("enter")
elif event.type() == QEvent.Type.HoverMove:
print("move")
elif event.type() == QEvent.Type.HoverLeave:
print("leave")
return super().eventFilter(obj, event)
if __name__ == "__main__":
app = QApplication(sys.argv)
window = MainApp()
window.show()
sys.exit(app.exec())

Implement Popup mapping in QSystemTrayIcon

I want to implement behaviour of a popup-window exactly like default volume controller in windows 10. One click on icon, window opens or closes; if window is opened, clicking outside it will close the window. How can i implement this?
Before, i found that it is possible for the widget to override the methods for pressing and releasing the mouse keys, but here it was not found, or it was poorly searched. Help me please.
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QLabel, QGridLayout, \
QWidget, QSystemTrayIcon, QStyle, qApp
import PyQt5.QtCore
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setMinimumSize(PyQt5.QtCore.QSize(600, 130))
self.setMaximumSize(PyQt5.QtCore.QSize(600, 130))
self.setWindowFlags(PyQt5.QtCore.Qt.Popup)
screen_geometry = QApplication.desktop().availableGeometry()
screen_size = (screen_geometry.width(), screen_geometry.height())
win_size = (self.frameSize().width(), self.frameSize().height())
x = screen_size[0] - win_size[0]
y = screen_size[1] - win_size[1]
self.move(x, y)
self.setWindowOpacity(0.85)
self.setWindowTitle("System Tray Application")
central_widget = QWidget(self)
self.setCentralWidget(central_widget)
grid_layout = QGridLayout(central_widget)
grid_layout.addWidget(QLabel("Application, which can minimize to tray",
self), 0, 0)
self.tray_icon = QSystemTrayIcon(self)
self.tray_icon.setIcon(self.
style().standardIcon(QStyle.SP_ComputerIcon))
self.tray_icon.activated.connect(self.trigger)
self.tray_icon.show()
self.setGeometry(500, 570, 600, 130)
self.fl = False
def trigger(self, reason):
if reason == QSystemTrayIcon.MiddleClick:
qApp.quit()
elif reason == QSystemTrayIcon.Trigger:
if not self.fl:
self.show()
else:
self.hide()
self.fl = not self.fl
elif reason == 1:
self.fl = False
# def mouseReleaseEvent(self, event):
# self.hide()
# self.fl = False
if __name__ == "__main__":
app = QApplication(sys.argv)
mw = MainWindow()
mw.show()
sys.exit(app.exec())
If you want to toggle visibility then you must use the setVisible() and isVisible() methods:
import sys
from PyQt5.QtWidgets import (
QApplication,
QGridLayout,
QLabel,
QMainWindow,
QStyle,
QSystemTrayIcon,
QWidget,
)
from PyQt5.QtCore import Qt, QSize
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setFixedSize(600, 130)
self.setWindowFlag(Qt.Popup)
self.setWindowOpacity(0.85)
self.setWindowTitle("System Tray Application")
central_widget = QWidget()
self.setCentralWidget(central_widget)
grid_layout = QGridLayout(central_widget)
grid_layout.addWidget(QLabel("Application, which can minimize to tray"), 0, 0)
self.tray_icon = QSystemTrayIcon(self)
self.tray_icon.setIcon(self.style().standardIcon(QStyle.SP_ComputerIcon))
self.tray_icon.activated.connect(self.trigger)
self.tray_icon.show()
self.setGeometry(
QStyle.alignedRect(
Qt.LeftToRight,
Qt.AlignBottom | Qt.AlignRight,
self.window().size(),
QApplication.desktop().availableGeometry(),
)
)
def trigger(self, reason):
if reason == QSystemTrayIcon.MiddleClick:
QApplication.quit()
elif reason == QSystemTrayIcon.Trigger:
self.setVisible(not self.isVisible())
if __name__ == "__main__":
app = QApplication(sys.argv)
mw = MainWindow()
mw.show()
sys.exit(app.exec())

Zoom in and out in widget

How can I make a zoom effect with key input on a widget? The widget is inside a scroll area and there are some drawings made with QPainter who change with user input. The zoom would affect the length of the scrolling bar, the closer you are, the smaller the bar becomes. The zoom at minimum level should make the scroll bar as big as the widget area, so all the content in the widget could be visualized.
MRE:
from PyQt5 import QtCore, QtWidgets
from PyQt5.QtWidgets import QWidget
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QPainter, QPen, QColor
import sys
class Diedrico(QWidget):
def __init__(self, parent):
super().__init__(parent)
def paintEvent(self, event):
qp = QPainter(self)
qp.setPen(QPen(QColor(Qt.black), 5))
qp.drawRect(500, 500, 1000, 1000)
class UiVentana(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super(UiVentana, self).__init__(parent)
self.resize(520, 520)
self.widget_central = QtWidgets.QWidget(self)
scrol = QtWidgets.QScrollArea(self.widget_central)
scrol.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
scrol.setGeometry(QtCore.QRect(10, 10, 500, 500))
scrol.setWidgetResizable(False)
contenido = QtWidgets.QWidget()
contenido.setGeometry(QtCore.QRect(0, 0, 2000, 2000))
scrol.setWidget(contenido)
self.Diedrico = Diedrico(contenido)
self.Diedrico.setGeometry(QtCore.QRect(0, 0, 2000, 2000))
self.setCentralWidget(self.widget_central)
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
ui = UiVentana()
ui.show()
sys.exit(app.exec_())
Why do you want to reinvent the wheel? Instead of wanting to implement the logic of the scaling feature, use the classes that already do it. In this case, a good option is to use QGraphicsView with QGraphicsScene:
Note: The shortcut standard Zoom In and Zoom Out are associated with Ctrl + + and Ctrl + -, respectively.
from PyQt5 import QtCore, QtGui, QtWidgets
class Diedrico(QtWidgets.QWidget):
def paintEvent(self, event):
qp = QtGui.QPainter(self)
pen = QtGui.QPen(QtGui.QColor(QtCore.Qt.black), 5)
qp.setPen(pen)
qp.drawRect(500, 500, 1000, 1000)
class UiVentana(QtWidgets.QMainWindow):
factor = 1.5
def __init__(self, parent=None):
super(UiVentana, self).__init__(parent)
self._scene = QtWidgets.QGraphicsScene(self)
self._view = QtWidgets.QGraphicsView(self._scene)
self._diedrico = Diedrico()
self._diedrico.setFixedSize(2000, 2000)
self._scene.addWidget(self._diedrico)
self.setCentralWidget(self._view)
QtWidgets.QShortcut(
QtGui.QKeySequence(QtGui.QKeySequence.ZoomIn),
self._view,
context=QtCore.Qt.WidgetShortcut,
activated=self.zoom_in,
)
QtWidgets.QShortcut(
QtGui.QKeySequence(QtGui.QKeySequence.ZoomOut),
self._view,
context=QtCore.Qt.WidgetShortcut,
activated=self.zoom_out,
)
#QtCore.pyqtSlot()
def zoom_in(self):
scale_tr = QtGui.QTransform()
scale_tr.scale(UiVentana.factor, UiVentana.factor)
tr = self._view.transform() * scale_tr
self._view.setTransform(tr)
#QtCore.pyqtSlot()
def zoom_out(self):
scale_tr = QtGui.QTransform()
scale_tr.scale(UiVentana.factor, UiVentana.factor)
scale_inverted, invertible = scale_tr.inverted()
if invertible:
tr = self._view.transform() * scale_inverted
self._view.setTransform(tr)
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
ui = UiVentana()
ui.show()
sys.exit(app.exec_())
Update:
If you want to use + and - for ZoomIn and ZoomOut, respectively, then just change the shortcuts to:
QtWidgets.QShortcut(
QtGui.QKeySequence(QtCore.Qt.Key_Plus), # <---
self._view,
context=QtCore.Qt.WidgetShortcut,
activated=self.zoom_in,
)
QtWidgets.QShortcut(
QtGui.QKeySequence(QtCore.Qt.Key_Minus), # <---
self._view,
context=QtCore.Qt.WidgetShortcut,
activated=self.zoom_out,
)

Disable specific keyboard event of qslider

I am using qslider in python 3. I can move cursor forward and backward by keyboard event of up, down, left and right arrow. I would like to disable specifically part of them: up and down arrow move cursor while right and left cursor do not. Is it possible to do that?
You have to override the keyPressEvent method:
from PyQt5 import QtCore, QtGui, QtWidgets
class Slider(QtWidgets.QSlider):
def keyPressEvent(self, event):
if event.key() in (QtCore.Qt.Key_Left, QtCore.Qt.Key_Right):
return
super(Slider, self).keyPressEvent(event)
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
w = QtWidgets.QWidget()
lay = QtWidgets.QHBoxLayout(w)
slider = Slider()
label = QtWidgets.QLabel(alignment=QtCore.Qt.AlignCenter)
slider.valueChanged.connect(label.setNum)
label.setNum(slider.value())
lay.addWidget(slider)
lay.addWidget(label)
w.resize(160, 240)
w.show()
sys.exit(app.exec_())

QRubberBand.geometry().intersects(???) How to find intersecting images in QGraphicsScene?

I found few codes which demonstrates intersects, but it was mainly buttons. Something like this:
for child in self.findChildren(QPushButton):
if rect.intersects(child.geometry( )):
selected.append(child)
But how do you find images intersecting in your GraphicsScene with "Marquee" selection(QRubberBand)? I tried replacing findChildren(QPushButton) with QPixmap, QGraphicsScene, QGraphicsPixmapItem it always giving me back empty list.
If you are using the QRubberBand that has the QGraphicsView you have to use the rubberBandChanged signal and next to the items method you get the items that are below the QRubberBand.
from PyQt5 import QtCore, QtGui, QtWidgets
import random
def create_pixmap():
pixmap = QtGui.QPixmap(100, 100)
pixmap.fill(QtGui.QColor(*random.sample(range(255), 3)))
return pixmap
class GraphicsView(QtWidgets.QGraphicsView):
def __init__(self, parent=None):
super(GraphicsView, self).__init__(parent)
self.setScene(QtWidgets.QGraphicsScene(self))
self.setDragMode(QtWidgets.QGraphicsView.RubberBandDrag)
self.rubberBandChanged.connect(self.on_rubberBandChanged)
for _ in range(5):
item = QtWidgets.QGraphicsPixmapItem(create_pixmap())
item.setPos(*random.sample(range(500), 2))
self.scene().addItem(item)
#QtCore.pyqtSlot("QRect", "QPointF", "QPointF")
def on_rubberBandChanged(
self, rubberBandRect, fromScenePoint, toScenePoint
):
r = QtCore.QRectF(fromScenePoint, toScenePoint)
selected = self.items(rubberBandRect)
print(selected)
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
w = GraphicsView()
w.resize(640, 480)
w.show()
sys.exit(app.exec_())
If you are using another QRubberBand the logic is similar to that since you must use the items() method of QGraphicsView
from PyQt5 import QtCore, QtGui, QtWidgets
import random
def create_pixmap():
pixmap = QtGui.QPixmap(100, 100)
pixmap.fill(QtGui.QColor(*random.sample(range(255), 3)))
return pixmap
class GraphicsView(QtWidgets.QGraphicsView):
def __init__(self, parent=None):
super(GraphicsView, self).__init__(parent)
self.setScene(QtWidgets.QGraphicsScene(self))
self._rubberBand = QtWidgets.QRubberBand(
QtWidgets.QRubberBand.Rectangle, self.viewport()
)
self._rubberBand.hide()
self._origin = QtCore.QPoint()
for _ in range(5):
item = QtWidgets.QGraphicsPixmapItem(create_pixmap())
item.setPos(*random.sample(range(500), 2))
self.scene().addItem(item)
def mousePressEvent(self, event):
self._origin = event.pos()
self._rubberBand.setGeometry(QtCore.QRect(self._origin, QtCore.QSize()))
self._rubberBand.show()
super(GraphicsView, self).mousePressEvent(event)
def mouseMoveEvent(self, event):
self._rubberBand.setGeometry(
QtCore.QRect(self._origin, event.pos()).normalized()
)
def mouseReleaseEvent(self, event):
self._rubberBand.setGeometry(
QtCore.QRect(self._origin, event.pos()).normalized()
)
selected = self.items(self._rubberBand.geometry())
print(selected)
self._rubberBand.hide()
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
w = GraphicsView()
w.resize(640, 480)
w.show()
sys.exit(app.exec_())

Categories