我有几个问题。我正在尝试创建一个自定义按钮,显示一个图标供用户点击。源图像是svg。
-
虽然我已经看到自定义按钮最常见的方式是使用ColorOverlay,但我不知何故无法做到这一点,因为根据此链接,QtGraphicalEffects似乎不是Qt6的一部分,因此我无法使用ColorOverlay。我正在用Python和Pyside6构建我的应用程序。
-
我也尝试使用Button.qml组件来实例化一个按钮,但我无法获得正确的搜索路径,因为它将从与Button.qml相同的目录中查找我的源图标图像,并且我不知道如何更改其搜索目录。
-
理想情况下,我希望能够使用qrc文件加载源图像,但我还没有找到在QML而不是Python中使用加载到qrc文件中的图像的方法。
以下是我尝试制作的带有自定义按钮的代码片段:
Rectangle{
width: 25
height: 25
color: "#00000000"
Image{
width: 24
height: 24
source: "random.svg"
}
MouseArea{
}
}
带QT按钮组件的按钮:
Button{
width: 25
height: 25
display: AbstractButton.IconOnly
icon.source: "random.svg"
}
对于问题1
Qt6.1包括Qt图形效果。
问题2
假设项目结构如此
-- project
-- main.qml
-- customs
-- Button.qml
-- icons
-- random.svg
在main.qml中,在命名空间下导入Button.qml。比方说Cust(它必须以大写字母开头(。
// main.qml
import QtQuick 2.15
import QtQuick.Controls 2.15
import "./customs" as Cust
Cust.Button {
}
这一次你100%肯定,你的会被加载。现在,在您的自定义Button.qml中添加源,您可以说它是相对于的
// Button.qml
Rectangle {
...
source: "./icons/random.svg"
}
如果自定义Button.qml代码本身与main.qml无关,比如Button.qml与main.qml不在同一文件夹中。您应该将该文件夹添加到QML2_IMPORT_PATH环境变量中,以便能够将其导入
例如。/路径/目的地/海关
您还需要该文件夹中的qmldir文件才能作为工作
// qmldir
module myCustomModule
Buttom 1.0 Button.qml
-- customs
-- qmldir
-- Button.qml
然后您可以将其作为导入main.qml中
// main.qml
import QtQuick 2.15
import QtQuick.Controls 2.15
import myCustomModule as Cust
Cust.Button {
}
如果你没有把你的名字也叫Button.qml,你叫它说MyButton.qml,你本可以做
// main.qml
import myCustomModule
MyButton {
}
这意味着您还必须在qmldir 中声明MyButton
问题3
您可以将QML文件中的qrc用作
source: "qrc:///random.svg"
这是严格的,而在python中你也可以这样做:
":/random.svg"