步骤1:定义
public:
void mousePressEvent(QMouseEvent *event);
void mouseMoveEvent(QMouseEvent *event);
void paintEvent(QPaintEvent *event);
QPoint DragPosition;
步骤2:构造函数中实现
QPixmap pix;
//加载图片
pix.load("11.png",0,Qt::AvoidDither|Qt::ThresholdDither| Qt::ThresholdAlphaDither);
resize(pix.size());//重设主窗体的尺寸为所读取的图片大小
setMask(QBitmap(pix.mask()));//遮住所选区域以外的部分
步骤3:使窗口可以拖动
void MainWindow::mousePressEvent(QMouseEvent *event)
{
if(event->button() == Qt::LeftButton)//判断按下的是否为鼠标左键
{
//DragPosition保存所在位置相对于左上角的偏移值
DragPosition = event->globalPos()-frameGeometry().topLeft();
event->accept();
}
if(event->button() == Qt::RightButton)//判断按下的是否为鼠标右键
{
close();
}
}
void MainWindow::mouseMoveEvent(QMouseEvent *event)
{
if(event->buttons() == Qt::LeftButton)//event->buttons()返回的是鼠标的状态
{
move(event->globalPos()-DragPosition);//移动到鼠标当前点
event->accept();
}
}
步骤4:使窗口显示为所读取的图片
void MainWindow::paintEvent(QPaintEvent *event)
{
QPainter painter(this);
painter.drawPixmap(0,0,QPixmap(“11.png”));
}