欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

动手做!用QT打造属于你的桌面小工具(第一篇)

最编程 2024-02-14 15:03:23
...
New script - 51cto.com.user.js:25 #include "widget.h"
#include "ui_widget.h"
#pragma execution_character_set("utf-8")

Widget::Widget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::Widget)
{
ui->setupUi(this);

setWindowTitle("vvcat");

//去窗口边框
setWindowFlags(Qt::FramelessWindowHint | windowFlags());

//把窗口背景设置为透明
setAttribute(Qt::WA_TranslucentBackground);

// 窗口置顶
setWindowFlags(windowFlags() | Qt::WindowStaysOnTopHint);


mSysTrayIcon = new QSystemTrayIcon(this);
mSysTrayIcon->setIcon(QIcon(":/icon/VVCAT.ico"));
mSysTrayIcon->setToolTip(QObject::trUtf8("vvcat"));
connect(mSysTrayIcon,SIGNAL(activated(QSystemTrayIcon::ActivationReason)),this,SLOT(on_activatedSysTrayIcon(QSystemTrayIcon::ActivationReason)));
connect(mSysTrayIcon,&QSystemTrayIcon::messageClicked,[&](){
this->show();

});

//建立托盘操作的菜单
createActions();
createMenu();
//在系统托盘显示此对象
mSysTrayIcon->show();

}

Widget::~Widget()
{
delete ui;
}

void Widget::paintEvent(QPaintEvent *){

QPainter p(this); //创建画家对象
p.begin(this);//指定当前窗口为绘图设备
p.drawPixmap(0, 0, QPixmap("../image/1.gif"));

}


//拖拽操作
void Widget::mousePressEvent(QMouseEvent *event)
{
if (event->button() == Qt::LeftButton)
{
m_bDrag = true ;
//获得鼠标的初始位置
mouseStartPoint = event->globalPos();

//获得窗口的初始位置
windowTopLeftPoint = this ->frameGeometry().topLeft();
}
}

void Widget::mouseMoveEvent(QMouseEvent *event)
{
if (m_bDrag)
{
//获得鼠标移动的距离
QPoint distance = event->globalPos() - mouseStartPoint;

//改变窗口的位置
this ->move(windowTopLeftPoint + distance);
}
}

void Widget::mouseReleaseEvent(QMouseEvent *event)
{
if (event->button() == Qt::LeftButton)
{
m_bDrag = false ;
}
}


void Widget::on_activatedSysTrayIcon(QSystemTrayIcon::ActivationReason reason)
{
switch(reason){
case QSystemTrayIcon::Trigger:
mSysTrayIcon->showMessage(QObject::trUtf8("vvcat"),QObject::trUtf8("welcome use me"),QSystemTrayIcon::Information, 1000);
break;
case QSystemTrayIcon::DoubleClick:
this->show();
break;
default:
break;
}
}

void Widget::createActions()
{
mShowMainAction = new QAction(QObject::trUtf8("Show"), this);
connect(mShowMainAction,SIGNAL(triggered()),this,SLOT(on_showMainAction()));

mHideAppAction = new QAction(QObject::trUtf8("Hide"), this);
connect(mHideAppAction,&QAction::triggered,[&](){this->hide();});

mExitAppAction = new QAction(QObject::trUtf8("Quit"), this);
connect(mExitAppAction,SIGNAL(triggered()), this, SLOT(on_exitAppAction()));
}

void Widget::createMenu()
{
mMenu = new QMenu(this);
mMenu->addAction(mShowMainAction);
mMenu->addAction(mHideAppAction);
mMenu->addAction(mExitAppAction);
mSysTrayIcon->setContextMenu(mMenu);
}

void Widget::on_showMainAction()
{
this->show();
}

void Widget::on_exitAppAction()
{
exit(0);
}