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

/ 44,285评论 / 217627阅读 / 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. Lazrhaw说道:

    Добрый день!
    Мы предлагаем дипломы любых профессий по приятным ценам.
    topairpack.com/диплом-купить-надежно

  2. Arnoldscava说道:

    medicine in mexico pharmacies buying prescription drugs in mexico mexican drugstore online

  3. Arnoldscava说道:

    mexican mail order pharmacies reputable mexican pharmacies online reputable mexican pharmacies online

  4. Waynetar说道:

    reputable mexican pharmacies online: buying prescription drugs in mexico – medicine in mexico pharmacies

  5. скачать популярные игры на телефон бесплатно http://www.android-games-download.ru .

  6. DominicHOr说道:

    purple pharmacy mexico price list: mexican online pharmacies prescription drugs – mexican border pharmacies shipping to usa

  7. Arnoldscava说道:

    buying prescription drugs in mexico online medicine in mexico pharmacies buying prescription drugs in mexico online

  8. NelsonSaIlk说道:

    medication from mexico pharmacy: mexican drugstore online – mexican pharmaceuticals online

  9. Waynetar说道:

    purple pharmacy mexico price list: pharmacies in mexico that ship to usa – reputable mexican pharmacies online

  10. Xazrqzh说道:

    Добрый день!
    Как оказалось, купить диплом кандидата наук не так уж и сложно
    arusak-diploms-srednee.ru/kupit-diplom-sssr

  11. Tooft说道:

    Public relations (PR) focuses on maintaining a positive image between a company individual and the public and media. This can be done by issuing press releases to the media, scheduling public appearances and managing bad publicity. eContent Pro powers all IGI Global Author Services. From this website, you will be able to receive your 10% discount (automatically applied at checkout), receive a free quote, place an order, and retrieve your final documents. Mass media is not a new way of mass communication. Since starting of civilisation, messages or information used to convey through Dhol, Nagara, etc. Now, the medium has been changed but still, the functions are same i.e. convey the messages to masses. Mass Media can be classified according to their physical form, the technology involved and the nature of the communication process. They are:
    https://marcolllj196418.bloginwi.com/61426455/article-under-review
    Having an extra day in Cleveland for a practice walkthrough won’t be a significant benefit for the New Orleans Saints (5-9), who’ll face the Browns (6-8) on Saturday at FirstEnergy Stadium. The Saints will depart for Cleveland after practice on Thursday, due to possible inclement weather on Friday, rather than Friday. Cleveland Browns quarterback Deshaun Watson said he is making progress as he continues his recovery on his surgically repaired throwing shoulder. Watson sustained the season-ending injury to his right shoulder during Cleveland’s 33-31 victory in Baltimore on Nov. His reinstatement comes nearly two years after Watson last played a regular-season game with the Texans in early January 2021. He was traded to the Browns this past spring and, having complied with the terms of the agreement established between him and the NFL in August, league spokesman Brian McCarthy said he is expected to make his scheduled return as planned. Watson will be eligible to play in Houston against his former team on Dec. 4.

  12. NelsonSaIlk说道:

    medicine in mexico pharmacies: medication from mexico pharmacy – mexican rx online

  13. BomesMix说道:

    Lorem Ipsum has been the industry’s standard dummy text https://innocap-goettingen.de/ixeit of type and scrambled it to make a type specimen book.

  14. DominicHOr说道:

    mexican border pharmacies shipping to usa: medication from mexico pharmacy – mexico drug stores pharmacies

  15. Trefmhq说道:

    Здравствуйте!
    Как официально купить диплом вуза с упрощенным обучением в Москве
    mipropuestadenegocio.com/category/uncategorized/page/3
    Будем рады вам помочь!.

  16. prodvizhen_vlpl说道:

    продвижение сайтов спб http://www.prodvizhenie-sajtov15.ru .

  17. Dnrtdjq说道:

    Добрый день!
    Приобрести документ о получении высшего образования можно в нашем сервисе.
    ast-diplomy24.ru/kupit-diplom-vracha
    Успехов в учебе!

  18. Arnoldscava说道:

    medicine in mexico pharmacies mexican mail order pharmacies reputable mexican pharmacies online

  19. Diplomi_azol说道:

    Здравствуйте!
    Заказать документ института вы сможете в нашей компании в столице.
    ast-diploms.com/kupit-diplom-kandidata-nauk

  20. Waynetar说道:

    mexican mail order pharmacies: mexico drug stores pharmacies – mexico drug stores pharmacies

  21. Lazrmks说道:

    Привет!
    Мы готовы предложить дипломы психологов, юристов, экономистов и прочих профессий по приятным тарифам.
    wildlifediaries.com/купить-диплом-новосибирск

  22. Arnoldscava说道:

    mexican rx online buying prescription drugs in mexico online buying prescription drugs in mexico online

  23. Arnoldscava说道:

    mexican pharmaceuticals online best online pharmacies in mexico mexican drugstore online

  24. Uazroid说道:

    Добрый день!
    Где купить диплом по актуальной специальности?
    obt.social/blogs/21773/Where-to-buy-a-diploma-at-an-adequate-price?lang=ar_sa

  25. 먹튀폴리스说道:

    Heya i am for the first time here. I came across this board and
    I find It really helpful & it helped me out a lot.
    I am hoping to offer one thing again and help others such as you
    aided me.

  26. Uazrxyc说道:

    Добрый день!
    Где заказать диплом по актуальной специальности?
    dzone.com/users/5166875/leonardchambers.html

  27. BomesMix说道:

    Lorem Ipsum has been the industry’s standard dummy text https://buytron.co.za/huodmx of type and scrambled it to make a type specimen book.

  28. NelsonSaIlk说道:

    mexican pharmaceuticals online: buying prescription drugs in mexico – mexican online pharmacies prescription drugs

  29. скачать топовые игры на андроид android-games-download.ru .

  30. RichardToone说道:

    An impressive story that tells the development of Romanian football genius Gheorghe Hagi https://galatasaray.gheorghe-hagi.net and his extraordinary achievements at the Turkish giant Galatasaray.

  31. NelsonSaIlk说道:

    mexican pharmaceuticals online: mexico pharmacies prescription drugs – pharmacies in mexico that ship to usa

  32. AustinWaync说道:

    Fernando Muslera https://galatasaray.fernandomuslera.net is one of the important players of Galatasaray. Find out about his contribution to the club’s success, his career in Europe and his personal life.

  33. RobertVam说道:

    From a young French https://real-madrid.zinedine-zidane-fr.com talent to a Real Madrid legend.

  34. Floyddiora说道:

    УК РФ Статья 228.1 Статья 228 УК РФ Незаконные производство, сбыт или пересылка наркотических средств, психотропных веществ или их аналогов.

  35. Diplomi_teol说道:

    Добрый день!
    Приобрести документ о получении высшего образования вы сможете в нашем сервисе.
    ast-diplom.com/kupit-diplom-perm

  36. Uazrtvk说道:

    Привет, друзья!
    Заказать диплом любого ВУЗа.
    transfer-tur.ru/ru/cb-profile/pluginclass/cbblogs?action=blogs&func=show&id=170

  37. Dnrthxn说道:

    Привет!
    Заказать документ о получении высшего образования вы можете в нашей компании в Москве.
    ast-diplomy.com/kupit-diplom-omsk
    Успешной учебы!

  38. Trefryt说道:

    Добрый день!
    Быстрое обучение и получение диплома магистра – возможно ли это?
    matthiasjakobbecker.com/купить-диплом-проверенные-способы
    Всегда вам поможем!.

  39. Waynetar说道:

    buying from online mexican pharmacy: п»їbest mexican online pharmacies – best online pharmacies in mexico

  40. Mazrmad说道:

    Привет, друзья!
    Рекомендации по безопасной покупке диплома о высшем образовании
    mans-diplomyxx.ru

  41. Waynetar说道:

    purple pharmacy mexico price list: mexican drugstore online – purple pharmacy mexico price list

  42. NelsonSaIlk说道:

    buying prescription drugs in mexico online: mexico drug stores pharmacies – purple pharmacy mexico price list

  43. Dnrtyuz说道:

    Здравствуйте!
    Заказать документ института вы можете у нас в Москве.
    diploms-x.com/kupit-diplom-omsk
    Хорошей учебы!

  44. DominicHOr说道:

    medicine in mexico pharmacies: purple pharmacy mexico price list – mexico drug stores pharmacies

  45. DominicHOr说道:

    buying from online mexican pharmacy: mexican border pharmacies shipping to usa – medication from mexico pharmacy

  46. BomesMix说道:

    Lorem Ipsum has been the industry’s standard dummy text https://denverbar.es/jslnyrs of type and scrambled it to make a type specimen book.

  47. Lazrvsm说道:

    Здравствуйте!
    Мы можем предложить дипломы любой профессии по приятным тарифам.
    netglu.com/read-blog/120_vy-hotite-zakazat-diplom-u-proverennogo-proizvoditelya-zahodite?mode=day

发表回复

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