qt实现桌面弹幕

来源:互联网 发布:软件项目培训 编辑:程序博客网 时间:2024/05/02 02:06

新手上路第一次写点东西

就当笔记来看看


qt是一个跨平台C++图形用户界面应用程序开发框架,应用软件的图形拿qt来做是效率很快的,今天来实现一下桌面弹幕


首先完成一个弹幕类,共有继承于QLabel

class barrage : public QLabel
{
    Q_OBJECT
public:
    explicit barrage(QString str, QWidget *parent = 0);
private:
    QPropertyAnimation *animation;//动画效果
    ~barrage();
    int duration;//周期
    int pix;//字体大小 
};


弹幕的构造函数里面对弹幕路线.运动时间,字体大小进行初始化

barrage::barrage(QString str, QWidget *parent):
    QLabel(parent)
{
    int hlevel;
    int height=20;
    int width=str.size()*height;
    int desktop_high = QApplication::desktop()->height();
    hlevel=desktop_high/10*(qrand()%10);
    this->setText(str);
    this->setAlignment(Qt::AlignCenter);//居中
    this->resize(width,height);
    animation=new QPropertyAnimation(this,"geometry",this);
    animation->setDuration(10000);
    animation->setKeyValueAt(0, QRect(1920,hlevel , width, height));
    animation->setKeyValueAt(1, QRect(0-width, hlevel, width, height));
    animation->start();
    QFont font;
    font.setPixelSize(height);
    this->setFont(font);
}

接着写了一个MainScreen类 继承与QMainWindow作为主窗口,里面放了1000个弹幕类,

class MainScreen : public QMainWindow
{
    Q_OBJECT
public:
    explicit MainScreen(QWidget *parent = 0);
private:
      barrage *barage[1000];
      QPushButton *button;
      QLineEdit *edit;
      int barnum;//弹幕数量
signals:
public slots:
    void SendBar();//发射弹幕的槽
};

在构造函数里面里面先将背景透明 

    //桌面透明
    setAutoFillBackground(false);  //这个不设置的话就背景变黑
    setWindowFlags(Qt::FramelessWindowHint);
    setAttribute(Qt::WA_TranslucentBackground,true);
按钮和编辑框的通过setGeometry(int,int,int,int)来设置大小和位置

    //获取桌面大小
    int desktop_width = QApplication::desktop()->width();
    int desktop_high = QApplication::desktop()->height();
    this->resize (desktop_width, desktop_high);
    button =new QPushButton("发送弹幕",this);
    button->setGeometry(800,800,100,20);
    edit=new QLineEdit(this);
    edit->setGeometry(920,800,100,20);
最后将按钮和自己写的槽函数连接起来 实现点击按钮发射弹幕(实例化一个barrage)
最后实现效果如图