AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • Início
  • system&network
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • Início
  • system&network
    • Recentes
    • Highest score
    • tags
  • Ubuntu
    • Recentes
    • Highest score
    • tags
  • Unix
    • Recentes
    • tags
  • DBA
    • Recentes
    • tags
  • Computer
    • Recentes
    • tags
  • Coding
    • Recentes
    • tags
Início / coding / Perguntas / 79080076
Accepted
sil ora
sil ora
Asked: 2024-10-12 10:27:55 +0800 CST2024-10-12 10:27:55 +0800 CST 2024-10-12 10:27:55 +0800 CST

Como ocultar um QWidget quando o mouse estiver passando e reaparecer quando o mouse sair?

  • 772

Estou tentando criar um pequeno widget para exibir informações. Este widget foi criado para ficar sempre no topo e ficar oculto quando o mouse passar sobre ele, para que você possa clicar ou ver o que estiver abaixo dele sem interrupção, e então reaparecer quando o mouse sair deste widget. O problema que estou enfrentando atualmente é que, uma vez que o widget está oculto, não há pixel desenhado, portanto, nenhuma atividade do mouse é rastreada mais, o que imediatamente aciona o leaveEvent, portanto, o widget continua piscando. Aqui está um exemplo:

import sys
from PyQt5.QtWidgets import QApplication, QLabel, QVBoxLayout, QWidget
from PyQt5.QtCore import Qt

class TransparentWindow(QWidget):
    def __init__(self):
        super().__init__()

        # Set window attributes
        self.setWindowFlags(self.windowFlags() | Qt.FramelessWindowHint | Qt.WindowStaysOnTopHint) # | Qt.WindowTransparentForInput)
        self.setAttribute(Qt.WA_TranslucentBackground)
        self.setMouseTracking(True)
        
        # Set example text
        self.layout = QVBoxLayout()
        self.label = QLabel(self)
        self.label.setText("Hello, World!")
        self.label.setStyleSheet("background-color: rgb(255, 255, 255); font-size: 50px;")
        self.label.setAlignment(Qt.AlignCenter)
        self.layout.addWidget(self.label)
        self.setLayout(self.layout)
        
    def enterEvent(self, event):
        print("Mouse entered the window")
        self.label.setHidden(True)
        
    def leaveEvent(self, event):
        print("Mouse left the window")
        self.label.setHidden(False)

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = TransparentWindow()
    window.show()
    sys.exit(app.exec_())

Agora tentei adicionar um item Qwidget quase transparente abaixo dele para poder captar eventos do mouse com esses pixels quase transparentes:

    def __init__(self):
        super().__init__()

        # Set window attributes
        self.setWindowFlags(self.windowFlags() | Qt.FramelessWindowHint | Qt.WindowStaysOnTopHint)
        self.setAttribute(Qt.WA_TranslucentBackground)
        self.setMouseTracking(True)
        
        # Set example text
        self.layout = QVBoxLayout()
        self.label = QLabel(self)
        self.label.setText("Hello, World!")
        self.label.setStyleSheet("background-color: rgb(255, 255, 255); font-size: 50px;")
        self.label.setAlignment(Qt.AlignCenter)
        self.layout.addWidget(self.label)
        self.setLayout(self.layout)

        # Set an almost transparent widget
        self.box = QWidget(self)
        self.box.setStyleSheet("background-color: rgba(255, 255, 255, 0.01)")
        self.layout.addWidget(self.box)

que faz a parte de desaparecer e reaparecer funcionar. Mas não consigo mais clicar em nada que esteja abaixo dela. Tentei adicionar Qt.WindowTransparentForInput, mas ele tornou a janela transparente para eventos de entrada/saída também. Existe alguma solução para tornar esta janela transparente apenas para eventos de clique, mas não para eventos de entrada/saída? Ou preciso usar outras bibliotecas globais de rastreamento de mouse para fazer isso funcionar?


Plataforma: Windows 11 23H2


Obrigado por toda a ajuda! Foi assim que decidi implementar no momento:

import sys
from PyQt5.QtWidgets import QApplication, QLabel, QVBoxLayout, QWidget
from PyQt5.QtGui import QCursor
from PyQt5.QtCore import Qt, QTimer

class TransparentWindow(QWidget):
    def __init__(self):
        super().__init__()

        # Set window attributes
        self.setWindowFlags(self.windowFlags() | Qt.FramelessWindowHint | Qt.WindowStaysOnTopHint | Qt.Tool) # | Qt.WindowTransparentForInput)
        self.setAttribute(Qt.WA_TranslucentBackground)
        self.setMouseTracking(True)

        # Set example text
        self.layout = QVBoxLayout()
        self.label = QLabel(self)
        self.label.setText("Hello, World!")
        self.label.setStyleSheet("background-color: rgb(255, 255, 255); font-size: 50px;")
        self.label.setAlignment(Qt.AlignCenter)
        self.layout.addWidget(self.label)
        self.setLayout(self.layout)

        self.hidetimer = QTimer(self)
        self.hidetimer.setSingleShot(True)
        self.hidetimer.timeout.connect(self.hidecheck)
        self.hidecheckperiod = 300

    def hidecheck(self):
        if self.geometry().contains(QCursor.pos()):
            self.hidetimer.start(self.hidecheckperiod)
            return
        print("Showing.....")
        self.setHidden(False)
            
    def enterEvent(self, event):
        self.setHidden(True)
        self.hidetimer.start(self.hidecheckperiod)
        print("Hiding.....")

if __name__ == "__main__":

    app = QApplication(sys.argv)
    window = TransparentWindow()
    window.show()
    sys.exit(app.exec_())

if __name__ == "__main__":

    app = QApplication(sys.argv)
    window = TransparentWindow()
    window.show()
    sys.exit(app.exec_())
python
  • 2 2 respostas
  • 70 Views

2 respostas

  • Voted
  1. SodaCris
    2024-10-13T00:53:59+08:002024-10-13T00:53:59+08:00

    que tal simplesmente afastar a janela, podemos usar um cronômetro

    assim:

        def move_back(self):
            x, y = self.geometry().x(), self.geometry().y()
            self.move(x+300, y)
    
        def enterEvent(self, event):
            print("Mouse entered the window")
            # self.label.setHidden(True)
            x, y = self.geometry().x(), self.geometry().y()
            self.move(x-300, y)
    
            self.timer = QTimer()
            self.timer.setSingleShot(True)
            self.timer.timeout.connect(self.move_back)
            self.timer.start(3000)
    
    • 3
  2. Best Answer
    ekhumoro
    2024-10-13T18:29:47+08:002024-10-13T18:29:47+08:00

    Você pode sondar a posição do cursor para ver se ela está contida pela geometria da janela atual. Isso tem o benefício adicional de permitir um pequeno atraso, para que a janela não seja continuamente mostrada/oculta quando o cursor se move rapidamente sobre ela. O atraso pode ser configurável pelo usuário. Acho que isso deve funcionar em todas as plataformas, mas só testei no Linux.

    Aqui está uma demonstração básica:

    import sys
    from PyQt5.QtWidgets import QApplication, QLabel, QVBoxLayout, QWidget
    from PyQt5.QtGui import QCursor
    from PyQt5.QtCore import Qt, QTimer
    
    class TransparentWindow(QWidget):
        def __init__(self):
            super().__init__()
    
            # Set window attributes
            self.setWindowFlags(self.windowFlags() | Qt.FramelessWindowHint | Qt.WindowStaysOnTopHint) # | Qt.WindowTransparentForInput)
            self.setAttribute(Qt.WA_TranslucentBackground)
    
            # Set example text
            self.layout = QVBoxLayout()
            self.label = QLabel(self)
            self.label.setText("Hello, World!")
            self.label.setStyleSheet("background-color: rgb(255, 255, 255); font-size: 50px;")
            self.label.setAlignment(Qt.AlignCenter)
            self.layout.addWidget(self.label)
            self.setLayout(self.layout)
    
            self._timer = QTimer(self)
            self._timer.setInterval(500)
            self._timer.timeout.connect(self.pollCursor)
            self._timer.start()
    
        def pollCursor(self):
            over = self.geometry().contains(QCursor.pos())
            if over != self.isHidden():
                self.setHidden(over)
                self._timer.start()
                print("Mouse is over the window:", over)
    
    if __name__ == "__main__":
    
        app = QApplication(sys.argv)
        window = TransparentWindow()
        window.show()
        sys.exit(app.exec_())
    
    • 1

relate perguntas

  • Como divido o loop for em 3 quadros de dados individuais?

  • Como verificar se todas as colunas flutuantes em um Pandas DataFrame são aproximadamente iguais ou próximas

  • Como funciona o "load_dataset", já que não está detectando arquivos de exemplo?

  • Por que a comparação de string pandas.eval() retorna False

  • Python tkinter/ ttkboostrap dateentry não funciona quando no estado somente leitura

Sidebar

Stats

  • Perguntas 205573
  • respostas 270741
  • best respostas 135370
  • utilizador 68524
  • Highest score
  • respostas
  • Marko Smith

    Vue 3: Erro na criação "Identificador esperado, mas encontrado 'import'" [duplicado]

    • 1 respostas
  • Marko Smith

    Por que esse código Java simples e pequeno roda 30x mais rápido em todas as JVMs Graal, mas não em nenhuma JVM Oracle?

    • 1 respostas
  • Marko Smith

    Qual é o propósito de `enum class` com um tipo subjacente especificado, mas sem enumeradores?

    • 1 respostas
  • Marko Smith

    Como faço para corrigir um erro MODULE_NOT_FOUND para um módulo que não importei manualmente?

    • 6 respostas
  • Marko Smith

    `(expression, lvalue) = rvalue` é uma atribuição válida em C ou C++? Por que alguns compiladores aceitam/rejeitam isso?

    • 3 respostas
  • Marko Smith

    Quando devo usar um std::inplace_vector em vez de um std::vector?

    • 3 respostas
  • Marko Smith

    Um programa vazio que não faz nada em C++ precisa de um heap de 204 KB, mas não em C

    • 1 respostas
  • Marko Smith

    PowerBI atualmente quebrado com BigQuery: problema de driver Simba com atualização do Windows

    • 2 respostas
  • Marko Smith

    AdMob: MobileAds.initialize() - "java.lang.Integer não pode ser convertido em java.lang.String" para alguns dispositivos

    • 1 respostas
  • Marko Smith

    Estou tentando fazer o jogo pacman usando apenas o módulo Turtle Random e Math

    • 1 respostas
  • Martin Hope
    Aleksandr Dubinsky Por que a correspondência de padrões com o switch no InetAddress falha com 'não cobre todos os valores de entrada possíveis'? 2024-12-23 06:56:21 +0800 CST
  • Martin Hope
    Phillip Borge Por que esse código Java simples e pequeno roda 30x mais rápido em todas as JVMs Graal, mas não em nenhuma JVM Oracle? 2024-12-12 20:46:46 +0800 CST
  • Martin Hope
    Oodini Qual é o propósito de `enum class` com um tipo subjacente especificado, mas sem enumeradores? 2024-12-12 06:27:11 +0800 CST
  • Martin Hope
    sleeptightAnsiC `(expression, lvalue) = rvalue` é uma atribuição válida em C ou C++? Por que alguns compiladores aceitam/rejeitam isso? 2024-11-09 07:18:53 +0800 CST
  • Martin Hope
    The Mad Gamer Quando devo usar um std::inplace_vector em vez de um std::vector? 2024-10-29 23:01:00 +0800 CST
  • Martin Hope
    Chad Feller O ponto e vírgula agora é opcional em condicionais bash com [[ .. ]] na versão 5.2? 2024-10-21 05:50:33 +0800 CST
  • Martin Hope
    Wrench Por que um traço duplo (--) faz com que esta cláusula MariaDB seja avaliada como verdadeira? 2024-05-05 13:37:20 +0800 CST
  • Martin Hope
    Waket Zheng Por que `dict(id=1, **{'id': 2})` às vezes gera `KeyError: 'id'` em vez de um TypeError? 2024-05-04 14:19:19 +0800 CST
  • Martin Hope
    user924 AdMob: MobileAds.initialize() - "java.lang.Integer não pode ser convertido em java.lang.String" para alguns dispositivos 2024-03-20 03:12:31 +0800 CST
  • Martin Hope
    MarkB Por que o GCC gera código que executa condicionalmente uma implementação SIMD? 2024-02-17 06:17:14 +0800 CST

Hot tag

python javascript c++ c# java typescript sql reactjs html

Explore

  • Início
  • Perguntas
    • Recentes
    • Highest score
  • tag
  • help

Footer

AskOverflow.Dev

About Us

  • About Us
  • Contact Us

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve