python - 如何在 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'
解决方案
如果你想在 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_())
推荐阅读
- javascript - 在 React 中,为什么 setTimeout 中的 setState 只能与状态副本一起正常工作?
- python - 如何在虚拟环境中将 python 模块添加到 PYTHONPATH?
- javascript - 如何将 VeeValidate 与 vue-i18n 集成?
- python - 我可以为共享机器上的默认 dask 调度程序指定最大内存吗?
- docker - Docker镜像越来越大
- python - 无法弄清楚如何关闭打开的参考
- opencv - Android SDK 工具:OpenCV 需要 Android SDK 工具版本 14 或更新版本
- react-native - 不能在 react-native 元素的复选框中使用 lineHeight
- css - 如何在css中垂直设置所有箭头?
- multithreading - 如何在发出的信号上更改小部件的背景颜色