我正在尝试实现一个自定义按钮,该按钮具有 press()
和 release()
函数,当收到预期的按键事件时我会调用这些函数。在这些函数中,pressed()
和 released()
信号被调用。 released()
工作完美,但是当调用 pressed()
时,会显示错误:
TypeError: Property 'pressed' of object CustomButton_QMLTYPE_3(0x78214d8) is not a function
我的理论是,QML 无法区分按钮的 bool Pressed
属性和 pressed()
信号。这是一个错误还是我做错了什么?这是我所做的:
这是自定义按钮 qml 文件:
import QtQuick 2.10
import QtQuick.Controls 2.12
Button {
id: control
function press() {
down = true;
pressed();
}
function release() {
down = false;
released()
}
}
在下面的示例中,当按下或释放 F3 键时,我调用按钮功能,并希望它们到达我建立的连接。
CustomButton {
id: customButton
width: parent.width
height: parent.height
Connections {
target: customButton
onPressed: {
console.log("Custom button pressed!\n");
}
onReleased: {
console.log("Custom button released!\n")
}
}
}
focus: true
Keys.onPressed: {
if(event.key === Qt.Key_F3 && !event.isAutoRepeat) {
console.log("F3 Key pressed!")
customButton.press()
}
}
Keys.onReleased: {
if(event.key === Qt.Key_F3 && !event.isAutoRepeat) {
console.log("F3 Key released!")
customButton.release()
}
}
就像我说的那样,发布有效,但媒体有问题。我在控制台中看到这些行:
qml: F3 Key pressed!
qml: press function called
file:///D:/Projects/QmlExamples/qml/fxMenu/button/CustomButton.qml:10: TypeError: Property 'pressed' of object CustomButton_QMLTYPE_3(0x78214d8) is not a function
qml: F3 Key released!
qml: release function called
qml: Custom button released!
最佳答案
如果您想手动发出按下信号,请在 Button 对象中声明它:
Button {
id: control
signal pressed;
signal released;
function press() {
down = true;
pressed();
}
function release() {
down = false;
released()
}
onPressedChanged: {
if (down) {
release();
} else {
press();
}
}
}
正如您所提到的,还有一个名为“pressed”的 bool 属性,因此看起来 QML 引擎无法识别您的意图。
关于qt - QML 自定义按钮无法发出按下信号,因为它不是一个函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60484663/