建立一个QWidget类型的工程,在该cpp的构造函数中写入:
setWindowFlags(Qt::FramelessWindowHint |Qt::WindowStaysOnTopHint);//设置窗体标题栏隐藏并设置位于顶层
setMouseTracking(true);//可获取鼠标跟踪效果
在该头文件中写一些变量和事件
public:
QPoint move_point;//移动的距离
bool mouse_press;//鼠标按下
private:
void mousePressEvent(QMouseEvent *event);//鼠标按下事件
void mouseReleaseEvent(QMouseEvent *event);//鼠标释放事件
void mouseMoveEvent(QMouseEvent *event);//鼠标移动事件
在该cpp中写这三个函数的方法体
void windowTest::mousePressEvent(QMouseEvent *event)
{
if (event->button()==Qt::LeftButton)
{
mouse_press = true;
move_point = event->pos();
}
}
void windowTest::mouseReleaseEvent(QMouseEvent *event)
{
mouse_press = false;
}
void windowTest::mouseMoveEvent(QMouseEvent *event)
{
if (mouse_press)
{
QPoint move_pos = event->globalPos();
this->move(move_pos - move_point);
}
}
在构造函数中写入加载背景:
int width = this->width();
QToolButton *minButton = new QToolButton(this);
QToolButton *closeButton = new QToolButton(this);
QPixmap minPix = style()->standardPixmap(QStyle::SP_TitleBarMinButton);
QPixmap closePix = style()->standardPixmap(QStyle::SP_TitleBarCloseButton);
minButton->setIcon(minPix);
closeButton->setIcon(closePix);
minButton->setGeometry(width - 46, 5, 20, 20);
closeButton->setGeometry(width - 25, 5, 20, 20);
minButton->setToolTip(tr("最小化"));
closeButton->setToolTip(tr("关闭"));
minButton->setStyleSheet("background-color:transparent");
closeButton->setStyleSheet("background-color:transparent");
//这个是用图片作为背景
//QLabel *background = new QLabel(this);
//background->setPixmap(QPixmap("D:/greatmap/dev/trunk/bin/Resources/Styles/Style0/Images/Dialog/close.png"));
//background->setGeometry(0, 0, this->width(), this->height());
//background->setScaledContents(true);
QLabel *background = new QLabel(this);
background->setStyleSheet("background-color:blue");
background->setGeometry(0, 0, this->width(), this->height());
如何使用图片作为背景的话,重写paintEvent函数:
virtual void paintEvent(QPaintEvent *);
void windowTest::paintEvent(QPaintEvent *)
{
QBitmap bitmap(this->size());
bitmap.fill();
QPainter painter(&bitmap);
QPixmap pixmap("D:/greatmap/dev/trunk/bin/Resources/Styles/Style0/Images/Dialog/close.png");
painter.drawPixmap(this->rect(), pixmap);
}