1. 程式人生 > >QML實現彈幕功能

QML實現彈幕功能

彈幕在視訊網站上很流行。這裡用QML實現一下基本功能。主要用到了動畫以及動態建立元件的相關知識。

效果如下(圖片的動態效果不太好O(∩_∩)O哈哈~)


程式碼如下:

import QtQuick 2.9
import QtQuick.Controls 2.2

ApplicationWindow {
    visible: true
    width: 640
    height: 480
    title: qsTr("彈幕")

    Rectangle{
       anchors.fill: parent;
       id : window
       color: "black"
    }

    property var liststr: ["呵呵o(* ̄︶ ̄*)o","nihao","ceshisx","你是說","啥意思","哈哈"]
    property int index: 0

    //動態載入
    function addItem()
    {
       var oldy = Math.random()*500%200 ;
       for (var i = 0 ; i < 1; ++i)
       {
           var component = Qt.createComponent("qrc:/TextItem.qml");

           if (component.status == Component.Ready)
           {
               var textitem = component.createObject(window);
               oldy += 30;
               textitem.y = oldy;
               index = Number(oldy%5);
               textitem.textstr = liststr[index];
           }
       }
    }

    Component.onCompleted: {
            addItem();
    }

    Timer {
             interval: 1000; running: true; repeat: true
             onTriggered: addItem()
         }

}

元件程式碼TextItem.qml

import QtQuick 2.9
import QtQuick.Controls 2.2

Rectangle{
    id : root
    height: 30;
    property real endx: 500;
    property alias textstr: roottext.text
    Text {
        id : roottext
        color: Qt.rgba(Math.random()+0.1,Math.random()+0.05,Math.random(),1);
        font.pointSize: 15
    }
    NumberAnimation on  x{
        from : Math.random()*20
        to : endx ; duration:5000
        onStopped: root.destroy(1)
    }

}