首页 > 解决方案 > 如何在 QMainWindow 中显示发光的标签

问题描述

我试图弄清楚如何使用 RectangularGlow 创建一个带有 PyQt5 的发光标签,但我不知道 QML,我不知道该怎么做。这是我到目前为止所拥有的:example.qml:

import QtQuick 2.4
import QtQuick.Controls 1.3
import QtQuick.Layouts 1.1
import QtGraphicalEffects 1.12


Label {
    text: "Identifiant"
    
    width: 400
    height: 200

    Rectangle {
        id: background
        anchors.fill: parent
        color: "black"
    }

    RectangularGlow {
        id: effect
        anchors.fill: rect
        glowRadius: 10
        spread: 0.2
        color: "white"
        cornerRadius: rect.radius + glowRadius
    }

    Rectangle {
        id: rect
        color: "black"
        anchors.centerIn: parent
        width: Math.round(parent.width / 1.5)
        height: Math.round(parent.height / 2)
        radius: 25
    }
}

以及使用它的python代码:

import sys
from PyQt5.QtWidgets import QApplication
from PyQt5.QtQml import QQmlApplicationEngine
from PyQt5.QtWidgets import *

 
if __name__ == "__main__":
    app = QApplication(sys.argv)
    engine = QQmlApplicationEngine()
    engine.load('example.qml')
    label = engine.rootObjects()[0]
    
    win = QMainWindow()
    win.setCentralWidget(label)
    win.show()
    sys.exit(app.exec_())

但我得到这个错误:

Traceback (most recent call last):
  File "test2.py", line 16, in <module>
    win.setCentralWidget(label)
TypeError: setCentralWidget(self, QWidget): argument 1 has unexpected type 'QObject'

标签: pythonpyqt5qml

解决方案


如果你想在 Qt Widgets 中使用 qml 项目,那么你必须使用一个QQuickWidget(或QQuickView+ QWidget::createWindowContainer()):

import os.path
import sys

from PyQt5.QtCore import QUrl
from PyQt5.QtWidgets import QApplication, QMainWindow
from PyQt5.QtQuickWidgets import QQuickWidget

CURRENT_DIR = os.path.join(os.path.dirname(os.path.realpath(__file__)))


if __name__ == "__main__":
    app = QApplication(sys.argv)

    filename = os.path.join(CURRENT_DIR, "example.qml")

    qml_widget = QQuickWidget()
    qml_widget.setResizeMode(QQuickWidget.SizeRootObjectToView)
    qml_widget.setSource(QUrl.fromLocalFile(filename))

    win = QMainWindow()
    win.setCentralWidget(qml_widget)
    win.show()
    sys.exit(app.exec_())

推荐阅读