本文介绍了创建鼠标聚光灯的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个简单的应用程序,以在鼠标光标位置周围放置聚光灯(使其他所有内容变暗)并用鼠标移动聚光灯.

像这样:

我对 Qt 没有太多经验.我从

I am trying to create a simple app to put a spotlight around mouse cursor position (dim everything else) and move the spotlight with mouse.

Something like this:

I do not have much experience with Qt. I started with this example, but could not go far.

I created a window which stays on top and set its opacity. But I am not sure how to make part of it completely transparent.

解决方案

To set the transparent background color you must set the attribute Qt::WA_TranslucentBackground, and then you paint a rectangle minus a circle as shown below:

from PyQt5 import QtCore, QtGui, QtWidgets

class SpotlightWidget(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super(SpotlightWidget, self).__init__(parent, QtCore.Qt.WindowStaysOnTopHint)
        self.setAttribute(QtCore.Qt.WA_TranslucentBackground)
        self.setAttribute(QtCore.Qt.WA_TransparentForMouseEvents)
        self.showFullScreen()
        self.setMouseTracking(True)
        self.center = QtCore.QPoint()

        self.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
        self.quitAction = QtWidgets.QAction("Salir", self,shortcut="Ctrl+Q", triggered=self.close)
        self.addAction(self.quitAction)

    def mouseMoveEvent(self, event):
        self.center = event.pos()
        self.update()
        super(SpotlightWidget, self).mouseMoveEvent(event)

    def paintEvent(self, event):
        painter = QtGui.QPainter(self)
        painter.setPen(QtCore.Qt.NoPen)
        painter.setRenderHint(QtGui.QPainter.Antialiasing)
        painter.setBrush(QtGui.QColor(108, 119, 125, 220))
        radius = 100
        path = QtGui.QPainterPath()
        if not self.center.isNull():
            path.moveTo(self.center + radius/2*QtCore.QPoint(1, 0))
            path.arcTo(QtCore.QRectF(self.center - radius/2*QtCore.QPointF(1, 1), radius*QtCore.QSizeF(1, 1)), 0, 360)
        path.addRect(QtCore.QRectF(self.rect()))
        painter.drawPath(path)


if __name__ == '__main__':
    import sys

    app = QtWidgets.QApplication(sys.argv)
    w = SpotlightWidget()
    w.show()
    sys.exit(app.exec_())

这篇关于创建鼠标聚光灯的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-22 12:08