AllRight
AllRight

Reputation: 21

I can't override the focus switch event between QMainWindow and any other PyQt6 application

There is a class on QWidget that should not open as a second window, so I use Qt.WindowType.Popup. Everything works correctly until you click past the application window. The event reports that a click was made past the application window, but when I change focus to another application or desktop, my widget closes, which I don't need. Therefore, I tried to redefine the focus change event, but print("The focus is lost, but the window remains open.") does not work at all.

class AddFriendWidget(QWidget):
    def __init__(self, main_window):
        super().__init__()
        self.main_window = main_window
        self.init_ui()

    def init_ui(self):
        # Layout and widgets
        self.setFixedSize(300, 150)
        add_friend_layout = QVBoxLayout(self)

        self.info_label = QLabel("Enter friend's username:")
        add_friend_layout.addWidget(self.info_label)

        self.friend_input = QLineEdit()
        self.friend_input.setPlaceholderText("Friend's username")
        add_friend_layout.addWidget(self.friend_input)

        self.add_button = QPushButton("Add Friend")
        self.add_button.clicked.connect(self.add_friend)
        add_friend_layout.addWidget(self.add_button)

        self.cancel_button = QPushButton("Cancel")
        self.cancel_button.clicked.connect(self.close)
        add_friend_layout.addWidget(self.cancel_button)

        self.setWindowFlags(Qt.WindowType.FramelessWindowHint | Qt.WindowType.Popup)
        self.installEventFilter(self)

        return self

    def add_friend(self):
        """Handle adding friend logic here."""
        friend_name = self.friend_input.text().strip()
        if friend_name:
            print(f"Friend '{friend_name}' added.")
        else:
            self.info_label.setText("Please enter a valid username.")


    def eventFilter(self, source, event):
        if event.type() == QEvent.Type.MouseButtonPress:
            global_pos = event.globalPosition().toPoint()

            if not self.main_window.geometry().contains(global_pos):
                print("Clicked OUTSIDE the entire application!")
            elif not self.geometry().contains(global_pos):
                print("Clicked outside the widget, but inside the main window.")
            else:
                print("Clicked inside the widget!")

            print(self.isVisible())
            return True
        
        if event.type() == QEvent.Type.FocusOut and isinstance(event, QEvent.FocusOut):
            if event.reason() == Qt.FocusReason.ActiveWindowFocusReason:
                print("The focus is lost, but the window remains open.")
                event.ignore()  
                return True  

        return super().eventFilter(source, event)

Upvotes: 0

Views: 39

Answers (0)

Related Questions