首页 > 技术文章 > QWidget总结

ike_li 2020-07-30 13:41 原文

1. 取消窗体标题栏

FramelessWindowHint 无边框,设置FramelessWindowHint后,带来主要问题是无法移动窗口以及无法使用鼠标拖拽缩放窗口大小。

setWindowFlags(Qt::FramelessWindowHint |Qt::WindowStaysOnTopHint);

2.设置窗体背景透明

  可以实现窗体放一张图片,整个窗体只显示图片。

 

 

 setWindowFlags(Qt::WindowCloseButtonHint|Qt::FramelessWindowHint|Qt::WindowStaysOnTopHint);
 setAttribute(Qt::WA_TranslucentBackground);
lblIcon_=new QLabel(this);    
lblIcon_->setMinimumSize(QSize(40,40));
lblIcon_->setMaximumSize(QSize(40,40));
QPixmap pixmap = QPixmap::fromImage(QImage(":/image/msg_gray.png"));
QPixmap fitPixmap=pixmap.scaled(40,40,Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
lblIcon_->setPixmap(fitPixmap);

QVBoxLayout *v=new QVBoxLayout(this);
v->setMargin(0);
v->addWidget(lblIcon_);
setLayout(v);

 

 

3.移动窗体

3.1 event->globalPos()获取的鼠标位置是鼠标偏离电脑屏幕左上角(x=0,y=0)的位置;
3.2 pos()获取的位置是主窗口(widget窗口)左上角(边框的左上角,外左上角)相对于电脑屏幕的左上角的(x=0,y=0)偏移位置;

3.3 event->globalY()<pos().y()+60 在窗体什么位置移动,通常都是点击住标题栏位置移动窗体。

bool is_move_window_;
QPoint move_window_pos_;

#include <QApplication>
#include <QMouseEvent>

void MainWidget::mousePressEvent(QMouseEvent *event)
{
    is_move_window_ = true;
    move_window_pos_ = event->globalPos() - pos();
    return QWidget::mousePressEvent(event);
}

void MainWidget::mouseMoveEvent(QMouseEvent *event)
{

    if (is_move_window_ && (event->buttons() && Qt::LeftButton)
       && (event->globalPos()-move_window_pos_).manhattanLength() > QApplication::startDragDistance()
       &&(event->globalY()<pos().y()+60))
    {
      move(event->globalPos()-move_window_pos_);
      move_window_pos_ = event->globalPos() - pos();
    }

    return QWidget::mouseMoveEvent(event);
}

void MainWidget::mouseReleaseEvent(QMouseEvent *event)
{
    is_move_window_=false;
}

 

4.获取电脑屏幕分辨率

 

QRect rect=QGuiApplication::primaryScreen()->geometry();
this->move(rect.width()-50,rect.height()-100);

 

 

 

推荐阅读