I'm trying to get mouse position(in-window) whenever the left mouse button is pressed using:
def mousePressEvent(self, event):
print(event.pos())
however, any kind of interactive widget overrides it, for example- clicking a button doesn't print mouse position, same with line edit and others(maybe except label). How would I get the mouse position even if those widgets are clicked?
Explanation:
In the case of QWidgets, you have to take into account:
The transmission of the mouse event is from the top widget(child) to the bottom widget(parent).
If an element consumes the mouse event (ie use event.accept()) then that event will no longer be transmitted.
Solution:
If you want to detect the mouse event on a window then you could monitor that event on the window itself (QWindow) through an eventfilter:
import sys
from PyQt5.QtCore import pyqtSignal, QEvent, QObject, QPoint
from PyQt5.QtWidgets import (
QApplication,
QLineEdit,
QPushButton,
QTextEdit,
QVBoxLayout,
QWidget,
)
class MouseHelper(QObject):
pressed = pyqtSignal(QPoint)
released = pyqtSignal(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() == QEvent.MouseButtonPress:
self.pressed.emit(event.pos())
elif event.type() == QEvent.MouseButtonRelease:
self.released.emit(event.pos())
return super().eventFilter(obj, event)
class Widget(QWidget):
def __init__(self, parent=None):
super().__init__(parent)
button = QPushButton("Press me")
lineedit = QLineEdit()
textedit = QTextEdit()
lay = QVBoxLayout(self)
lay.addWidget(button)
lay.addWidget(lineedit)
lay.addWidget(textedit)
if __name__ == "__main__":
app = QApplication(sys.argv)
w = Widget()
w.show()
helper = MouseHelper(w.windowHandle())
helper.pressed.connect(lambda point: print("pressed:", point))
helper.released.connect(lambda point: print("released:", point))
sys.exit(app.exec_())
Related
So I want to grab the QFrame and scroll it, so I'm using mouse-move-event to do it, but the problem I have is the event triggers even when I click outside the Frame that I set Mouse Tracking on. So I thought of stopping at least the mouse-Move-Event early at mouse-press-event, but the problem is the focusWidget method always returns the scroll area, so I can't filter out the other widgets, and the ignore method doesn't stop the chain of events execution.
Code Demo:
import sys
from PyQt5.QtWidgets import (QApplication, QMainWindow, QWidget,
QVBoxLayout, QFrame, QScrollArea)
class Window(QMainWindow):
def __init__(self):
super(Window, self).__init__()
"""supposed to stop the events' chain when it's not the scrolling frame"""
def mousePressEvent(self, event):
if QApplication.focusWidget()!=scroll:
print("ignore")
event.ignore()
def mouseMoveEvent(self, event):
print("move")
app = QApplication(sys.argv)
layout = QVBoxLayout()
b_widget=QFrame()
b_widget.setStyleSheet("background-color: blue")
b_widget.setMinimumSize(100, 50)
r_widget=QFrame()
r_widget.setStyleSheet("background-color: red")
r_widget.setMinimumSize(100, 50)
g_widget=QFrame()
g_widget.setStyleSheet("background-color: green")
g_widget.setMinimumSize(1000, 1000)
"""activating mouse tracking on the scrolling frame"""
g_widget.setMouseTracking(True)
scroll=QScrollArea()
scroll.setWidget(g_widget)
layout.addWidget(r_widget)
layout.addWidget(b_widget)
layout.addWidget(scroll)
widget = QWidget()
widget.setLayout(layout)
main=Window()
main.setCentralWidget(widget)
main.show()
app.exec()
Thank you for your help.
Im using PyQT5 and Python Version is 3.78.
I got a request than when I mouse over the button and display menubar.I made that code and it works.
import sys
from PyQt5 import QtWidgets
from PyQt5.QtCore import Qt, QEvent
from PyQt5.QtGui import QIcon, QFont
from PyQt5.QtWidgets import (QApplication, QMainWindow, QAction, qApp, QInputDialog, QLineEdit)
from app.strategy.menu_strategy import MenuStrategy
class DrawMenuWnd(QMainWindow):
def __init__(self, title, parent=None):
super(DrawMenuWnd, self).__init__(parent)
self.ctrl = None # source from wnd hook event
# self.menu_stg_obj = MenuStrategy(state_mq) # stop operation when input sth..
# set title
self.setWindowTitle(title)
# set win size and attrs
self.setGeometry(100, 100, 100, 100)
self.setWindowFlags(Qt.FramelessWindowHint | Qt.Tool | Qt.WindowStaysOnTopHint)
self.initial_ui()
def initial_ui(self):
self.menubar = self.menuBar()
self.menubar.setFont(QFont('微软雅黑'))
self.coin = QIcon(r'./arrow.jpeg')
# root menu
self.root_menu = self.menubar.addMenu(self.coin, "")
# mouse child menu
self.left_single = QAction("left click", self)
self.left_double_single = QAction("left double click", self)
self.right_single = QAction("right click", self)
self.root_menu.addAction(self.left_single)
self.root_menu.addAction(self.left_double_single)
self.root_menu.addAction(self.right_single)
# seperator
self.root_menu.addSeparator()
# keyboard child menu
self.input = QAction("keyboard input", self)
self.root_menu.addAction(self.input)
# connect function
# self.left_single.triggered.connect(self.menu_stg_obj.click)
# self.left_double_single.triggered.connect(self.menu_stg_obj.double_click)
# self.right_single.triggered.connect(self.menu_stg_obj.right_click)
# self.input.triggered.connect(self.menu_stg_obj.keyboard_input)
# set event filter
self.menubar.installEventFilter(self)
#classmethod
def initial_menu(cls, title):
app = QtWidgets.QApplication(sys.argv)
window = DrawMenuWnd(title)
window.show()
app.exec_()
def eventFilter(self, object, event):
try:
if event.type() == QEvent.Enter:
print("Mouse is over the label")
if self.root_menu.isHidden():
self.root_menu.show()
# print('program stop is', self.stop)
return True
elif event.type() == QEvent.Leave:
print("Mouse is not over the label")
self.root_menu.hide()
# print('program stop is', self.stop)
return False
except Exception as error:
print(error)
if __name__ == '__main__':
app = QApplication(sys.argv)
window = DrawMenuWnd("")
window.show()
sys.exit(app.exec())
Now I got a question that when I mouse away from button, the menubar should disappear but now not.
So now I wanna let the menubar disappear after my mouse away from the button, I try to hide the menubar in using function hide() but it not works
Anybody help?
thanks
What I meant is something like that :
import sys
from PyQt5 import QtWidgets
from PyQt5.QtCore import Qt, QEvent
from PyQt5.QtGui import QIcon, QFont
from PyQt5.QtWidgets import (QApplication, QMainWindow, QAction, qApp, QInputDialog, QLineEdit,QMenu)
class MyQMenu(QMenu):
def __init__(self, *args, **kwargs):
QMenu.__init__(self, *args, **kwargs)
def leaveEvent(self, QEvent):
# here the code for mouse leave
self.close()
print('Leave')
class DrawMenuWnd(QMainWindow):
def __init__(self, title, parent=None):
super(DrawMenuWnd, self).__init__(parent)
self.ctrl = None # source from wnd hook event
# self.menu_stg_obj = MenuStrategy(state_mq) # stop operation when input sth..
# set title
self.setWindowTitle(title)
# set win size and attrs
self.setGeometry(100, 100, 100, 100)
self.setWindowFlags(Qt.FramelessWindowHint | Qt.Tool | Qt.WindowStaysOnTopHint)
self.initial_ui()
def initial_ui(self):
self.menubar = self.menuBar()
self.menubar.setFont(QFont('微软雅黑'))
self.coin = QIcon(r'./arrow.jpeg')
# root menu
self.root_menu = MyQMenu( "")
self.root_menu.setIcon(self.coin)
self.menubar.addMenu(self.root_menu)
# mouse child menu
self.left_single = QAction("left click", self)
self.left_double_single = QAction("left double click", self)
self.right_single = QAction("right click", self)
self.root_menu.addAction(self.left_single)
self.root_menu.addAction(self.left_double_single)
self.root_menu.addAction(self.right_single)
# seperator
self.root_menu.addSeparator()
# keyboard child menu
self.input = QAction("keyboard input", self)
self.root_menu.addAction(self.input)
# connect function
# self.left_single.triggered.connect(self.menu_stg_obj.click)
# self.left_double_single.triggered.connect(self.menu_stg_obj.double_click)
# self.right_single.triggered.connect(self.menu_stg_obj.right_click)
# self.input.triggered.connect(self.menu_stg_obj.keyboard_input)
# set event filter
self.menubar.installEventFilter(self)
#classmethod
def initial_menu(cls, title):
app = QtWidgets.QApplication(sys.argv)
window = DrawMenuWnd(title)
window.show()
app.exec_()
def eventFilter(self, object, event):
try:
if event.type() == QEvent.Enter:
print("Mouse is over the label")
if self.root_menu.isHidden():
self.root_menu.show()
# print('program stop is', self.stop)
return True
elif event.type() == QEvent.Leave:
print("Mouse is not over the label")
self.root_menu.hide()
# print('program stop is', self.stop)
return False
except Exception as error:
print(error)
if __name__ == '__main__':
app = QApplication(sys.argv)
window = DrawMenuWnd("")
window.show()
sys.exit(app.exec())
I'm trying to add custom animation to QPushbutton without making a custom QPushbutton and overriding its enterEvent() and leaveEvent().
So far I've tried this,
#staticmethod
def addButtonHoverAnimation(button:QPushButton,currentPos:QPoint):
'''
Method to:
=> Add hover animation for provided button
'''
enterShift = QPropertyAnimation(button,b'pos',button)
exitShift = QPropertyAnimation(button,b'pos',button)
def enterEvent(e):
pos=button.pos()
enterShift.setStartValue(pos)
enterShift.setEndValue(QPoint(pos.x()+3,pos.y()+3))
enterShift.setDuration(100)
enterShift.start()
Effects.dropShadow(button,1,2)
def leaveEvent(e):
pos=button.pos()
exitShift.setStartValue(pos)
exitShift.setEndValue(QPoint(pos.x()-3,pos.y()-3))
exitShift.setDuration(100)
exitShift.start()
Effects.dropShadow(button)
button.enterEvent=enterEvent
button.leaveEvent=leaveEvent
But when I move the mouse very quickly in and out of the button before the animation finishes, The button starts to move wierdly towards the North-West direction.
Button Animation Using Dynamic Positions
I figured out this was due to the leaveEvent() being triggered before enterEvent() even finishes and also because the start and end values are dynamic. So, I tried providing currentPos as a static position and using it instead,
#staticmethod
def addButtonHoverAnimation(button:QPushButton,currentPos:QPoint):
'''
Method to:
=> Add hover animation for provided button
'''
enterShift = QPropertyAnimation(button,b'pos',button)
enterShift.setStartValue(currentPos)
enterShift.setEndValue(QPoint(currentPos.x()+3,currentPos.y()+3))
enterShift.setDuration(100)
exitShift = QPropertyAnimation(button,b'pos',button)
exitShift.setStartValue(QPoint(currentPos.x()-3,currentPos.y()-3))
exitShift.setEndValue(currentPos)
exitShift.setDuration(100)
def enterEvent(e):
button.setProperty(b'pos',exitShift.endValue())
enterShift.start()
Effects.dropShadow(button,1,2)
def leaveEvent(e):
exitShift.start()
Effects.dropShadow(button)
button.enterEvent=enterEvent
button.leaveEvent=leaveEvent
On running, as soon as the mouse enters the QPushbutton, it moves to the top-left of its parent widget and the animation starts working fine. I can't figure out why this is happening. But I was able to get that, it only happened when I used any static value in the animation.
Button Animation with Static Position:
Here is an example:
import sys
from PyQt5.QtCore import QEvent, QPoint, QObject, QPropertyAnimation
from PyQt5.QtWidgets import QApplication, QPushButton, QVBoxLayout, QWidget
# This is the same method mentioned above
from styling import addButtonHoverAnimation
class Widget(QWidget):
def __init__(self, parent=None):
super().__init__(parent)
layout=QVBoxLayout()
button1 = QPushButton("Proceed1", self)
layout.addWidget(button1)
button2 = QPushButton("Proceed2", self)
layout.addWidget(button2)
self.setLayout(layout)
self.resize(640, 480)
addButtonHoverAnimation(button1)
addButtonHoverAnimation(button2)
def main():
app = QApplication(sys.argv)
view = Widget()
view.show()
ret = app.exec_()
sys.exit(ret)
if __name__ == "__main__":
main()
The problem is that probably when the state is changed from enter to leave (or vice versa) the previous animation still does not end so the position of the widget is not the initial or final position, so when starting the new animation there is a deviation that accumulates. One possible solution is to initialize the position and keep it as a reference.
On the other hand you should not do x.fooMethod = foo_callable since many can fail, in this case it is better to use an eventfilter.
import sys
from dataclasses import dataclass
from functools import cached_property
from PyQt5.QtCore import QEvent, QPoint, QObject, QPropertyAnimation
from PyQt5.QtWidgets import QApplication, QPushButton, QWidget
#dataclass
class AnimationManager(QObject):
widget: QWidget
delta: QPoint = QPoint(3, 3)
duration: int = 100
def __post_init__(self):
super().__init__(self.widget)
self._start_value = QPoint()
self._end_value = QPoint()
self.widget.installEventFilter(self)
self.animation.setTargetObject(self.widget)
self.animation.setPropertyName(b"pos")
self.reset()
def reset(self):
self._start_value = self.widget.pos()
self._end_value = self._start_value + self.delta
self.animation.setDuration(self.duration)
#cached_property
def animation(self):
return QPropertyAnimation(self)
def eventFilter(self, obj, event):
if obj is self.widget:
if event.type() == QEvent.Enter:
self.start_enter_animation()
elif event.type() == QEvent.Leave:
self.start_leave_animation()
return super().eventFilter(obj, event)
def start_enter_animation(self):
self.animation.stop()
self.animation.setStartValue(self.widget.pos())
self.animation.setEndValue(self._end_value)
self.animation.start()
def start_leave_animation(self):
self.animation.stop()
self.animation.setStartValue(self.widget.pos())
self.animation.setEndValue(self._start_value)
self.animation.start()
class Widget(QWidget):
def __init__(self, parent=None):
super().__init__(parent)
button1 = QPushButton("Proceed1", self)
button1.move(100, 100)
button2 = QPushButton("Proceed2", self)
button2.move(200, 200)
self.resize(640, 480)
animation_manager1 = AnimationManager(widget=button1)
animation_manager2 = AnimationManager(widget=button2)
def main():
app = QApplication(sys.argv)
view = Widget()
view.show()
ret = app.exec_()
sys.exit(ret)
if __name__ == "__main__":
main()
184 / 5000
Resultados de traducción
If you are using a layout then you must reset the position since the layout does not apply the position change immediately but only when the parent widget applies the changes.
class Widget(QWidget):
def __init__(self, parent=None):
super().__init__(parent)
button1 = QPushButton("Proceed1")
button2 = QPushButton("Proceed2")
lay = QVBoxLayout(self)
lay.addWidget(button1)
lay.addWidget(button2)
self.resize(640, 480)
self.animation_manager1 = AnimationManager(widget=button1)
self.animation_manager2 = AnimationManager(widget=button2)
def resizeEvent(self, event):
super().resizeEvent(event)
self.animation_manager1.reset()
self.animation_manager2.reset()
I want to get the position of mouse while it's hovering over a label. I read this but my problem is different. I need to grab the mouse position as it hovers over my label without clicking so, mouseMoveEvent doesn't help
here's my code:
class MyWindow(QMainWindow):
def __init__(self):
super().__init__()
self.WindowGUI()
self.level = "Image Not Loaded Yet"
self.mouseIsClicked = False
self.top = 90
self.left = 90
self.height = 1800
self.width = 1800
self.setGeometry(self.top, self.left, self.height, self.width)
self.setWindowTitle("Manual Contact Andgle")
self.setMouseTracking(True)
mainWidget = QWidget(self)
self.setCentralWidget(mainWidget)
mainWidget.setLayout(self.finalVbox)
self.show()
def WindowGUI(self):
self.finalVbox = QVBoxLayout() # Final Layout
self.mainHBox = QHBoxLayout() # Hbox for picLable and Buttons
self.mainVBox = QVBoxLayout() # VBox for two Groupboxes
self.lineVBox = QVBoxLayout() # VBox For Line Drawing Buttons
self.fileVBox = QVBoxLayout() # VBox for file Loading and Saving Buttons
self.lineGroupbox = QGroupBox("Drawing") # GroupBox For Line Drawing Buttons
self.fileGroupbox = QGroupBox("File") # GroupBox for File Loading and Saving Buttons
self.picLable = Label(self) # Lable For showing the Image
self.piclable_pixmap = QPixmap("loadImage.png") # Setting Pixmap
self.picLable.setPixmap(self.piclable_pixmap) # setting pixmap to piclable
def mouseMoveEvent(self, QMouseEvent):
print(QMouseEvent.pos())
If you want to detect the mouse position without pressing on the widget then you must enable mouseTracking that will make the mouseMoveEvent invoked when the mouse is pressed or not, if you want to verify that it is not pressed you must use the buttons() method:
import sys
from PyQt5 import QtWidgets
class Label(QtWidgets.QLabel):
def __init__(self, parent=None):
super().__init__(parent)
self.setMouseTracking(True)
def mouseMoveEvent(self, event):
if not event.buttons():
print(event.pos())
super().mouseMoveEvent(event)
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
w = Label()
w.resize(640, 480)
w.show()
sys.exit(app.exec_())
UPDATE:
Mouse events are propagated from children to parents if the children do not consume it, that is, if the child consumes it then the parent cannot consume it. So the QLabel is consuming that event so the window will not be notified, so in this case an eventFilter should be used:
import sys
from PyQt5.QtCore import pyqtSignal, pyqtSlot, QEvent, QObject, QPoint
from PyQt5.QtGui import QPixmap
from PyQt5.QtWidgets import QApplication, QLabel, QMainWindow
class HoverTracker(QObject):
positionChanged = pyqtSignal(QPoint)
def __init__(self, widget):
super().__init__(widget)
self._widget = widget
self.widget.setMouseTracking(True)
self.widget.installEventFilter(self)
#property
def widget(self):
return self._widget
def eventFilter(self, obj, event):
if obj is self.widget and event.type() == QEvent.MouseMove:
self.positionChanged.emit(event.pos())
return super().eventFilter(obj, event)
class MyWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("Manual Contact Andgle")
self.picLable = QLabel(self)
self.picLable.setPixmap(QPixmap("loadImage.png"))
hover_tracker = HoverTracker(self.picLable)
hover_tracker.positionChanged.connect(self.on_position_changed)
#pyqtSlot(QPoint)
def on_position_changed(self, p):
print(p)
if __name__ == "__main__":
app = QApplication(sys.argv)
w = MyWindow()
w.resize(640, 480)
w.show()
sys.exit(app.exec_())
You can use enterEvent.
Enter event gets called everytime the mouse is over the widget. With the event.pos() you can get the mouse coordinates.
self.label.enterEvent = lambda event: print(event.pos())
So the idea is that I should be able to fire up the script, select a portion of the screen, then hit enter (or otherwise trigger it) to save the selection.
I've got a good bit of the code from other posts and things, but now I'm stuck. I can select any portion of the screen and resize as needed, but I can't seem to get it to recognize the "enter" key. Right now the "keyPressEvent" function is just supposed to print a message so I know it worked, but I got nothing. Any ideas?
import sys
from PyQt5 import QtGui, QtCore, QtWidgets
from PyQt5.QtCore import Qt, QPoint, QRect, QSize
from PyQt5.QtGui import QScreen
from PyQt5.QtWidgets import QApplication, QLabel, QRubberBand
class MyLabel(QtWidgets.QLabel):
def __init__(self, parent=None):
QtWidgets.QLabel.__init__(self, parent)
self.selection = QtWidgets.QRubberBand(QtWidgets.QRubberBand.Rectangle, self)
def keyPressEvent(self, qKeyEvent):
print(qKeyEvent.key())
if qKeyEvent.key() == QtCore.Qt.Key_Return:
print('Enter pressed')
else:
super().keyPressEvent(qKeyEvent)
def mousePressEvent(self, event):
'''
Mouse is pressed. If selection is visible either set dragging mode (if close to border) or hide selection.
If selection is not visible make it visible and start at this point.
'''
if event.button() == QtCore.Qt.LeftButton:
position = QtCore.QPoint(event.pos())
if self.selection.isVisible():
# visible selection
if (self.upper_left - position).manhattanLength() < 20:
# close to upper left corner, drag it
self.mode = "drag_upper_left"
elif (self.lower_right - position).manhattanLength() < 20:
# close to lower right corner, drag it
self.mode = "drag_lower_right"
else:
# clicked somewhere else, hide selection
self.selection.hide()
else:
# no visible selection, start new selection
self.upper_left = position
self.lower_right = position
self.mode = "drag_lower_right"
self.selection.show()
def mouseMoveEvent(self, event):
'''
Mouse moved. If selection is visible, drag it according to drag mode.
'''
if self.selection.isVisible():
# visible selection
if self.mode is "drag_lower_right":
self.lower_right = QtCore.QPoint(event.pos())
elif self.mode is "drag_upper_left":
self.upper_left = QtCore.QPoint(event.pos())
# update geometry
self.selection.setGeometry(QtCore.QRect(self.upper_left, self.lower_right).normalized())
class mainUI(QtWidgets.QWidget):
def __init__(self):
super(mainUI, self).__init__()
self.initUI()
def initUI(self):
layout = QtWidgets.QVBoxLayout(self)
label = MyLabel(self)
pixmap = QScreen.grabWindow(app.primaryScreen(), app.desktop().winId())
label.setPixmap(pixmap)
layout.addWidget(label)
self.setLayout(layout)
geometry = app.desktop().availableGeometry()
self.setFixedSize(geometry.width(), geometry.height())
# self.setWindowFlags( self.windowFlags() | Qt.FramelessWindowHint)
self.show()
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
window = mainUI()
sys.exit(app.exec_())
EDIT
Alright this code works, although to be honest I'm not 100% sure why.
import sys
from PyQt5 import QtGui, QtCore, QtWidgets
from PyQt5.QtCore import Qt, QPoint, QRect, QSize
from PyQt5.QtGui import QScreen
from PyQt5.QtWidgets import QApplication, QLabel, QRubberBand, QAction
class KpeWindow(QtWidgets.QLabel):
def __init__(self, parent=None):
QtWidgets.QLabel.__init__(self,parent)
main = QtWidgets.QVBoxLayout(self)
self.selection = QtWidgets.QRubberBand(QtWidgets.QRubberBand.Rectangle, self)
# label = QLabel(self)
# label.setText('Test the keyPressEvent')
# main.addWidget(label)
# self.adjustSize()
# self.setLayout(main)
def keyPressEvent(self, event):
print(event.key())
if event.key() == QtCore.Qt.Key_Return:
print('yay')
#QtWidgets.QMessageBox.warning(self, 'MDI', 'keyPressEvent')
self.parent().keyPressEvent(event)
def mousePressEvent(self, event):
'''
Mouse is pressed. If selection is visible either set dragging mode (if close to border) or hide selection.
If selection is not visible make it visible and start at this point.
'''
print(event)
if event.button() == QtCore.Qt.LeftButton:
position = QtCore.QPoint(event.pos())
if self.selection.isVisible():
# visible selection
if (self.upper_left - position).manhattanLength() < 20:
# close to upper left corner, drag it
self.mode = "drag_upper_left"
elif (self.lower_right - position).manhattanLength() < 20:
# close to lower right corner, drag it
self.mode = "drag_lower_right"
else:
# clicked somewhere else, hide selection
self.selection.hide()
else:
# no visible selection, start new selection
self.upper_left = position
self.lower_right = position
self.mode = "drag_lower_right"
self.selection.show()
def mouseMoveEvent(self, event):
'''
Mouse moved. If selection is visible, drag it according to drag mode.
'''
if self.selection.isVisible():
# visible selection
if self.mode is "drag_lower_right":
self.lower_right = QtCore.QPoint(event.pos())
elif self.mode is "drag_upper_left":
self.upper_left = QtCore.QPoint(event.pos())
# update geometry
self.selection.setGeometry(QtCore.QRect(self.upper_left, self.lower_right).normalized())
class MainWindow(QtWidgets.QWidget):
def __init__(self):
super(MainWindow, self).__init__()
QtWidgets.QMainWindow.__init__(self)
#self.setWindowTitle('KeyPressEvent Test')
# main = QtWidgets.QVBoxLayout(self)
# child = KpeWindow(self)
# child.setFocusPolicy(Qt.StrongFocus)
# self.setFocusProxy(child)
# main.addWidget(child)
# child.setFocus(True)
layout = QtWidgets.QVBoxLayout(self)
label = KpeWindow(self)
pixmap = QScreen.grabWindow(app.primaryScreen(), app.desktop().winId())
label.setPixmap(pixmap)
layout.addWidget(label)
#new
label.setFocusPolicy(Qt.StrongFocus)
self.setFocusProxy(label)
label.setFocus(True)
self.setLayout(layout)
geometry = app.desktop().availableGeometry()
self.setFixedSize(geometry.width(), geometry.height())
# self.setWindowFlags( self.windowFlags() | Qt.FramelessWindowHint)
self.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
mainWin = MainWindow()
mainWin.show()
sys.exit(app.exec_())
You need to set the focus policy on the label to get keyboard events:
class MyLabel(QtWidgets.QLabel):
def __init__(self, parent=None):
...
self.setFocusPolicy(Qt.TabFocus)