dataved
dataved

Reputation: 82

No focus event for QWidget

Consider the following code. I run it on BeagleBone (libqt5widgets5:armhf 5.7.1+dfsg-3+b1). It does fire FocusInEvent event. When I replace QDialog with QWidget in the line (***), it stops working. Why?

This is not reproducible for a different PyQt5 installation (I use Cygwin to check).

[1] this may or may not be related to, :focus don't work in PyQt (QT 5.7) [2] same thing in C++ does not work either, https://github.com/leshikus/qt-test

#!/usr/bin/python3
# -*- coding: utf-8 -*-

import sys
from PyQt5.QtWidgets import QApplication, QWidget, QSlider, QCheckBox, QVBoxLayout, QMainWindow, QDialog
from PyQt5.QtCore import Qt, QEvent


class MyWidget(QSlider):
    def __init__(self):
        super().__init__()

    def focusInEvent(self, event):
        super().focusInEvent(event)
        print('focusInEvent')

    def focusOutEvent(self, event):
        super().focusOutEvent(event)
        print('focusOutEvent')

    def eventFilter(self, source, event):
        print("eventFilter", event.type(), source)
        return super().eventFilter(source, event)


if __name__ == '__main__':

    app = QApplication(sys.argv)

    w = QDialog() # got replaced with QWidget (***)
    w.resize(300, 200)
    w.move(30, 30)

    layout = QVBoxLayout()
    layout.setContentsMargins(0, 0, 0, 0)
    layout.setSpacing(0)

    s = MyWidget()
    layout.addWidget(s)
    w.setLayout(layout)

    s.installEventFilter(s)
    s.setFocus()
    w.show()

    sys.exit(app.exec_())

Upvotes: 1

Views: 2428

Answers (1)

gortsu
gortsu

Reputation: 126

You need to make your QWidget accept focus events by calling setFocusPolicy(Qt::FocusPolicy policy)

Check the C++ API for more info about focus policy.

Python-specific documentation is available for PyQt4

Upvotes: 2

Related Questions