How to fire mouse click event on clicking in year option for QCalendarWidget.
onclick of year(2012),
i want to print some text using pyqt5
Can anyone help. Thanks in advance/
The first thing is to obtain the QSpinBox that shows the year using findChildren, then it is to detect the mouse event but as this solution points out it is not possible so a workaround is to detect the focus event:
from PyQt5 import QtCore, QtWidgets
class MainWindow(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super().__init__(parent)
self.calendar_widget = QtWidgets.QCalendarWidget()
self.setCentralWidget(self.calendar_widget)
self.year_spinbox = self.calendar_widget.findChild(
QtWidgets.QSpinBox, "qt_calendar_yearedit"
)
self.year_spinbox.installEventFilter(self)
def eventFilter(self, obj, event):
if obj is self.year_spinbox and event.type() == QtCore.QEvent.FocusIn:
print(self.year_spinbox.value())
return super().eventFilter(obj, event)
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
w = MainWindow()
w.show()
sys.exit(app.exec_())
Related
I want to create a customizedwindow such that whenever window is deactivated.
The window becomes the 'active' window and regains the focus to the window
Below code is sort of working but randomly stops making the window 'active' after several window
deactivates, when this happens the app just blinks on the bottom of the toolbar or is just highlighted.
(Btw im using windows 7 if it matters)
from PyQt5.QtWidgets import QMainWindow, QApplication
from PyQt5 import QtCore
import sys
class myWindow(QMainWindow):
def __init__(self, parent=None):
super(myWindow, self).__init__(parent)
self.installEventFilter(self)
self.counter = 0
def eventFilter(self, obj, event):
if event.type() == QtCore.QEvent.WindowDeactivate:
self.counter += 1
print(self.counter)
self.raise_()
self.activateWindow()
return False
return False
if __name__ == '__main__':
app = QApplication(sys.argv)
win = myWindow()
win.show()
sys.exit(app.exec())
I found a better implementation using win32gui and win32com.client, I think it depends on which os you're using since the previous (while loop implementation) wasnt working with windows 10. Had this working for several pc's now
from PyQt5.QtWidgets import QMainWindow, QApplication
from PyQt5 import QtCore
import sys
import win32gui
import win32com.client
class myWindow(QMainWindow):
def __init__(self, parent=None):
super(myWindow, self).__init__(parent)
self.installEventFilter(self)
self.counter = 0
def eventFilter(self, obj, event):
if event.type() == QtCore.QEvent.WindowDeactivate:
if not self.isActiveWindow():
self.refocus_window()
return False
return False
def refocus_window():
try:
hwnd = win32gui.FindWindow(None, 'Repair')
win32gui.ShowWindow(hwnd, 9)
shell = win32com.client.Dispatch('WScript.Shell')
shell.SendKeys('%')
win32gui.SetForegroundWindow(hwnd)
except Exception as err:
raise err
if __name__ == '__main__':
app = QApplication(sys.argv)
win = myWindow()
win.show()
sys.exit(app.exec())
Im using QFileSystemModel and QTreeView in my application(Pyqt5). I was looking for a way which I can clear file selection when press on the white blank area... to be more specific im need a way to know how to check whether the user press on the blank area in order to not choose at any file.
You have to detect the click with an event filter and then determine if a valid QModelIndex is associated, and in the case of the empty area it is not associated with a QModelIndex:
import os
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
CURRENT_DIR = os.path.dirname(os.path.realpath(__file__))
class MainWindow(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.model = QtWidgets.QFileSystemModel(self)
self.view = QtWidgets.QTreeView()
self.setCentralWidget(self.view)
self.view.setModel(self.model)
self.view.viewport().installEventFilter(self)
path = CURRENT_DIR
self.model.setRootPath(path)
self.view.setRootIndex(self.model.index(path))
def eventFilter(self, obj, event):
if (
obj is self.view.viewport()
and event.type() == QtCore.QEvent.MouseButtonDblClick
):
ix = self.view.indexAt(event.pos())
if not ix.isValid():
print("empty area")
self.view.clearSelection()
return super(MainWindow, self).eventFilter(obj, event)
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
w = MainWindow()
w.show()
sys.exit(app.exec_())
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_())
I'm trying to detect mouse clicks for anywhere inside an area with several widgets. For this I'm using the following code:
custom_widget = CustomWidget()
custom_widget.mouse_pressed_signal.connect(self.on_custom_label_mouse_pressed)
main_layout_vbox.addWidget(custom_widget)
hbox = QtWidgets.QHBoxLayout()
custom_widget.setLayout(hbox)
# Adding several widgets to hbox_l6
class CustomWidget(QtWidgets.QWidget):
mouse_pressed_signal = QtCore.pyqtSignal(QtGui.QMouseEvent)
def __init__(self):
super().__init__()
def mousePressEvent(self, i_qmouseevent):
super(CustomWidget, self).mousePressEvent(i_qmouseevent)
logging.debug("======== CustomWidget - mousePressEvent ========")
self.mouse_pressed_signal.emit(i_qmouseevent)
Problem
This works when clicking in any of the child widgets, but there's a problem: If I click between widgets (so in the area of the hbox layout that is not covered by a widget) the mousePressEvent is not captured
Question
How can I solve this problem? (Or is there another approach that you can recommend?) The important thing is that I am able to capture mouse clicks anywhere inside of custom_widget / hbox (see code above)
If you want to listen to other widget's mousePressEvent you can use an eventFilter as I show below:
from PyQt5 import QtCore, QtGui, QtWidgets
import random
class Widget(QtWidgets.QWidget):
mouse_clicked_signal = QtCore.pyqtSignal(QtGui.QMouseEvent, QtWidgets.QWidget)
def __init__(self, parent=None):
super(Widget, self).__init__(parent)
hlay = QtWidgets.QHBoxLayout(self)
for cls in (QtWidgets.QLabel, QtWidgets.QPushButton, QtWidgets.QFrame, QtWidgets.QWidget):
widget = cls()
color = QtGui.QColor(*random.sample(range(255), 3))
widget.setStyleSheet("background-color: {}".format(color.name()))
hlay.addWidget(widget)
for w in self.findChildren(QtWidgets.QWidget) + [self]:
w.installEventFilter(self)
self.resize(640, 480)
def eventFilter(self, watched, event):
if event.type() == QtCore.QEvent.MouseButtonPress:
self.mouse_clicked_signal.emit(event, watched)
return super(Widget, self).eventFilter(watched, event)
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
w = Widget()
w.mouse_clicked_signal.connect(print)
w.show()
sys.exit(app.exec_())
Hi guys im new in python and PyQt already im using PyQt 5 lib and already faced with really primary problem.
I want to call print function (or any other functions like this) with just cursor moving no clicking on that.
some thing like tooltips that not needed to click on any button.
Thank you for your help.
There are several ways to implement:
1. customized button.
from PyQt5 import QtCore, QtWidgets
class HoverButton(QtWidgets.QPushButton):
hovered = QtCore.pyqtSignal()
def enterEvent(self, event):
self.hovered.emit()
super(HoverButton, self).enterEvent(event)
class Widget(QtWidgets.QWidget):
def __init__(self, parent=None):
super(Widget, self).__init__(parent)
lay = QtWidgets.QVBoxLayout(self)
btn = HoverButton("Press me")
btn.hovered.connect(self.onHovered)
lay.addWidget(btn)
lay.addWidget(QtWidgets.QLineEdit())
def onHovered(self):
print("hovered")
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
w = Widget()
w.show()
sys.exit(app.exec_())
2. eventFilter
from PyQt5 import QtCore, QtWidgets
class Widget(QtWidgets.QWidget):
def __init__(self, parent=None):
super(Widget, self).__init__(parent)
lay = QtWidgets.QVBoxLayout(self)
self.btn = QtWidgets.QPushButton("Press me")
self.btn.installEventFilter(self)
lay.addWidget(self.btn)
lay.addWidget(QtWidgets.QLineEdit())
def eventFilter(self, obj, event):
if obj == self.btn and event.type() == QtCore.QEvent.HoverEnter:
self.onHovered()
return super(Widget, self).eventFilter(obj, event)
def onHovered(self):
print("hovered")
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
w = Widget()
w.show()
sys.exit(app.exec_())