Qt第十五章:QML之自定义按钮

女爷i 2024-04-01 08:34 192阅读 0赞

1.什么是按钮?矩形+文字+图片+点击事件

  1. import QtQuick 6.3
  2. Item{
  3. id:item0
  4. width:300
  5. height:300
  6. //背景图
  7. Image{
  8. width:300
  9. height:300
  10. source:"./DeepBlue.png"
  11. }
  12. //自定义一个变量来记录点击次数
  13. property int count: 0
  14. //矩形
  15. Rectangle{
  16. id: rectangle0
  17. //点击的时候控件缩小一点
  18. width: mouseArea0.containsPress?95:100
  19. height: mouseArea0.containsPress?18:20
  20. anchors.centerIn: parent
  21. radius:5
  22. //鼠标悬停改变一下颜色
  23. color: mouseArea0.containsMouse?"green":"cyan"
  24. //显示文字
  25. Text{
  26. id: text0
  27. text: "点击了【"+item0.count+"】次"
  28. anchors.centerIn: parent
  29. }
  30. //点击事件
  31. MouseArea{
  32. id: mouseArea0
  33. anchors.fill: parent
  34. //鼠标悬浮
  35. hoverEnabled: true
  36. onClicked: x => {
  37. item0.count++
  38. }
  39. }
  40. }
  41. }

2984f7ad715347e8a6540ea16b68938d.png

2.组件化

  1. import QtQuick 6.3
  2. Rectangle{
  3. id: root
  4. //提供一个点击信号给使用者
  5. signal clicked()
  6. //提供内部的text0对象给使用者
  7. property alias text0:text0
  8. //点击的时候控件缩小一点
  9. width: mouseArea0.containsPress?width*0.8:100
  10. height: mouseArea0.containsPress?height*0.8:20
  11. radius:5
  12. //鼠标悬停改变一下颜色
  13. color: mouseArea0.containsMouse?"green":"cyan"
  14. //显示文字
  15. Text{
  16. id: text0
  17. text: "自定义按钮"
  18. anchors.centerIn: parent
  19. }
  20. //点击事件
  21. MouseArea{
  22. id: mouseArea0
  23. anchors.fill: parent
  24. //鼠标悬浮
  25. hoverEnabled: true
  26. onClicked: x => {
  27. root.clicked()
  28. }
  29. }
  30. }

1a17fb84070e4ee68a2f04df4f717629.png

3.使用

  1. import QtQuick 6.3
  2. //如果在相同文件夹下,则无需导入
  3. //import "qrc:/qml"
  4. Item{
  5. MindButtion{
  6. onClicked:{
  7. Qt.quit()
  8. }
  9. }
  10. MindButtion{
  11. text0.text:"灵魂痛击"
  12. y:100
  13. }
  14. }

43c63a3e2fcd4b8c82bed4a58eab4daa.png

发表评论

表情:
评论列表 (有 0 条评论,192人围观)

还没有评论,来说两句吧...

相关阅读

    相关 QtQMLItem

    Item是Qt Quick中所有可视组件的基本类型,Qt Quick中的所有可视组件都继承于Item。它定义了所有可视组件的通用属性,如坐标、宽高、锚定关系、事件处理等等。