有一个类QWidget不应该作为第二个窗口打开,因此我使用Qt.WindowType.Popup。
一切工作正常,直到您单击应用程序窗口。Event它说
在应用程序窗口外进行了点击,但是当将焦点转移到另一个应用程序或桌面时,我的小部件会关闭,这不是我想要的。所以我尝试重新定义event焦点变化,但
print("The focus is lost, but the window remains open.")根本不起作用。
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
# Проверяем, является ли событие фокусировки QFocusEvent, прежде чем обращаться к `reason()`
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)