在QML语言中怎么定义signal并怎么正确使用
答案:1 悬赏:70 手机版
解决时间 2021-11-07 22:56
- 提问者网友:精神病院里
- 2021-11-07 12:42
在QML语言中怎么定义signal并怎么正确使用
最佳答案
- 五星知识达人网友:底特律间谍
- 2021-11-07 14:15
三种方法。一种是直接把信号的第一个字母变为大写, 并同时在前面加上"on“。第二种方法使用”Connections"来实现槽的连接。第三种方法,我们可以直接 把信号连接到一个JS的函数上。运行程序,我们可以在应用的输出窗口看到如下的输出:
[cpp] view plain copy
green light is on
yellow light is on
red light is on
red light is on
yellow light is on
green light is on
yellow light is on
red light is on
red light is on
yellow light is on
事实上所有的控件的property都可以发出一个信号。让我们来看一下我们先前完成的“color” property。
[cpp] view plain copy
void TrafficLight::setColor(const QColor &color)
{
if ( color == m_color )
return;
else {
m_color = color;
update(); // repaint with the new color
emit colorChanged();
}
}
从这里可以看出,每当property的值发生改变时,就会发生一个叫做“colorChanged”的信号。我们可以在我们的QML中截获这个信号。比如在我们的代码中,我们可以使用如下的代码:
[cpp] view plain copy
TrafficLight{
id: redlight
width: background.size
height: background.size
color:"red"
onColorChanged: {
console.log("Color is changed to " + color);
}
}
当我们运行时,我们可以看到好多的颜色变化的事件。这是由于颜色在transition时发生很多的颜色的变化。同样我们也可以对任何一个property进行事件的捕获。比如:
[cpp] view plain copy
TrafficLight{
id: redlight
width: background.size
height: background.size
color:"red"
onColorChanged: {
console.log("Color is changed to " + color);
}
onWidthChanged: {
console.log("width is changed to " + width);
}
}
这段代码可以对"width"的变化进行捕获!
[cpp] view plain copy
green light is on
yellow light is on
red light is on
red light is on
yellow light is on
green light is on
yellow light is on
red light is on
red light is on
yellow light is on
事实上所有的控件的property都可以发出一个信号。让我们来看一下我们先前完成的“color” property。
[cpp] view plain copy
void TrafficLight::setColor(const QColor &color)
{
if ( color == m_color )
return;
else {
m_color = color;
update(); // repaint with the new color
emit colorChanged();
}
}
从这里可以看出,每当property的值发生改变时,就会发生一个叫做“colorChanged”的信号。我们可以在我们的QML中截获这个信号。比如在我们的代码中,我们可以使用如下的代码:
[cpp] view plain copy
TrafficLight{
id: redlight
width: background.size
height: background.size
color:"red"
onColorChanged: {
console.log("Color is changed to " + color);
}
}
当我们运行时,我们可以看到好多的颜色变化的事件。这是由于颜色在transition时发生很多的颜色的变化。同样我们也可以对任何一个property进行事件的捕获。比如:
[cpp] view plain copy
TrafficLight{
id: redlight
width: background.size
height: background.size
color:"red"
onColorChanged: {
console.log("Color is changed to " + color);
}
onWidthChanged: {
console.log("width is changed to " + width);
}
}
这段代码可以对"width"的变化进行捕获!
我要举报
如以上问答信息为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
大家都在看
推荐资讯