[Qt/qml]程序之外显示的弹幕

/ 27,590评论 / 151946阅读 / 4点赞

前几天课设做个聊天系统,顺便实现了这个在程序外显示弹幕作为消息提示的功能,这里记录一下怎么搞。

效果

思路

实操

import QtQuick 2.3
import QtQuick.Controls 2.5
//窗口
ApplicationWindow  {
    id:root
    property string str: "我的洛天依"  //弹幕文本内容
    width: 300
    height: 40

    flags:  Qt.FramelessWindowHint  //去掉窗口标题栏
    color:"#00000000"   //设置背景透明

    Rectangle {     //使用矩形包裹Text是为了在Text外面可以增加圆角矩形边框效果
        anchors.fill: parent
        border.width: 1     //设置边框
        border.color: "#66ccff"
        color:"#00000000"
        radius: 20          //边框圆角
        clip: true          //超出矩形范围的内容隐藏

        Text {      //弹幕文本
            anchors.fill: parent
            text: str
            font.bold: true
            font.pointSize: 15
            color: "#66ccff"
            style: Text.Outline     //设置文本样式,在字体轮廓加一层styleColor指定的颜色边缘,防止背景导致文本不明显
            styleColor: "#fff"
            horizontalAlignment: Text.AlignHCenter  //居中
            verticalAlignment:   Text.AlignVCenter
            clip: true
        }
    }
}
import QtQuick
import QtQuick.Window 2.3
import QtQuick.Controls 2.5

Window {
    id:mainWin
    width: 700
    height: 500
    visible: true
    title: qsTr("MimicryChat")

    //添加弹幕
    function addBarrage(in_str) {
        var newCom = Qt.createComponent("Barrage.qml");   //创建弹幕窗口
        var newWin = newCom.createObject();
        newWin.x   = 200;
        newWin.y   = Math.random() * 900;   //随机竖直位置
        newWin.str = in_str;   //设置弹幕文本
        newWin.show();         //显示弹幕窗口

        //设置定时控制器
        let timer = Qt.createQmlObject("import QtQuick 2.14; Timer {}", mainWin);
        timer.interval = 20;    //执行间隔时间(单位ms)
        timer.repeat = true;    //重复执行
        timer.triggered.connect(function() {  //执行内容
            if(newWin.x < 1700) {  //如果没到右边缘就移动2个像素点
                newWin.x += 2;
            } else {
                timer.stop();      //到达右边缘,则停止定时控制器,并销毁弹幕
                newWin.close();
            }
        });
        timer.start();   //启动定时器
    }
    Rectangle {   //主窗口背景颜色
        anchors.fill: parent
        color: "#dde8fc"
        radius: 20
    }
    Button {
        width:100
        height: 40
        text:"发送弹幕"
        anchors.bottom: parent.bottom
        anchors.bottomMargin: 10
        //水平居中
        anchors.horizontalCenter: parent.horizontalCenter
        onClicked: {
            addBarrage("嘿嘿,我的洛天依");
        }
    }
}

问题

  1. Michaelsew说道:

    https://mexicoph24.life/# buying from online mexican pharmacy

  2. JustinTut说道:

    Online medicine order https://indiaph24.store/# cheapest online pharmacy india
    online pharmacy india

  3. JustinTut说道:

    online pharmacy india http://indiaph24.store/# reputable indian pharmacies
    online shopping pharmacy india

  4. JustinTut说道:

    indianpharmacy com https://indiaph24.store/# top online pharmacy india
    top 10 online pharmacy in india

  5. JustinTut说道:

    pharmacy website india https://indiaph24.store/# best online pharmacy india
    mail order pharmacy india

  6. JustinTut说道:

    indianpharmacy com https://indiaph24.store/# pharmacy website india
    india pharmacy

  7. Приветствуем ваш сайт!

    К вам обращается компания СЕО продвижения XRumer LLC.

    Ваш интернет-сайт, как мы заметили, еще только начинает набирать обороты. Чтобы максимально ускорить его рост, предлагаем услуги по внешней SEO-оптимизации. Полное продвижение в поисковиках – наша специализация. В ассортименте представлены эффективные SEO-инструменты для экспертов. Наши специалисты обладают большим опытом и портфолио успешных проектов, которыми мы поделимся по вашему запросу.

    Мы готовы предложить скидку 10% до конца месяца.

    Что мы готовы предложить:

    – Размещаем трастовые ссылки (требуется каждому сайту) – от 1,5 до 5000 руб

    – Безанкорные ссылки (2500 штук) (рекомендуется всем сайтам) – 3900 руб

    – Качественный прогон по 110000 сайтам в RU.зоне (максимально полезно для сайта) – 2900 рублей

    – 150 постов в VK про ваш сайт (отличная реклама) – 3900 руб

    – Публикация статей о вашем сайте на 300 топовых интернет-форумах (мощнейшая раскрутка интернет-сайта) – 29 тыс. рублей

    – СуперПостинг – отличный прогон по 3 000 000 площадок (очень мощный прогон для ваших сайтов) – 39 тыс р

    – Рассылаем рекламные сообщения по сайтам используя форму обратной связи – договорная цена, зависит от объемов.

    Со всеми вопросами обращайтесь, отвечаем быстро.

    Telegram: @xrumers
    https://XRumer.cc/
    Skype: Loves.Ltd

  8. JustinTut说道:

    top 10 pharmacies in india http://indiaph24.store/# best india pharmacy
    reputable indian pharmacies

  9. Michaelsew说道:

    http://canadaph24.pro/# trustworthy canadian pharmacy

  10. StevenSen说道:

    canadian pharmacy ed medications: Licensed Canadian Pharmacy – buying drugs from canada

  11. oborudovan_kiSl说道:

    оборудование для ситуационного центра https://oborudovanie-situacionnyh-centrov.ru/ .

  12. StevenSen说道:

    buy medicines online in india: indian pharmacy – india online pharmacy

  13. roma99说道:

    Hey I know this is off topic but I was wondering if you knew
    of any widgets I could add to my blog that automatically tweet my newest twitter updates.
    I’ve been looking for a plug-in like this for quite some time and was hoping maybe you would have some experience with something like this.
    Please let me know if you run into anything. I truly enjoy reading your blog and I look forward to your new updates.

  14. Protect your financial privacy with TornadoCash. Safeguard your transactions from prying eyes on the blockchain

回复 zestril 5mg 取消回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注