win32加qt怎么为窗口添加边框和通过鼠标更改窗口大小
时间: 2023-06-08 07:06:55 浏览: 334
您好,关于win32和QT的窗口开发问题,可以通过以下步骤为窗口添加边框和通过鼠标更改窗口大小:
1. 为窗口添加边框
使用QT的QMainWindow类可以很方便地实现窗口边框的添加。您可以在创建主窗口时设置其窗口样式为Qt::CustomizeWindowHint指定,然后在重写paintEvent方法时绘制边框、标题栏、按钮等元素。例如:
```c++
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
{
// 设置窗口样式
setWindowFlags(Qt::CustomizeWindowHint | Qt::WindowMinimizeButtonHint | Qt::WindowMaximizeButtonHint | Qt::WindowTitleHint);
setWindowTitle(tr("My Window"));
// 设置边框颜色和宽度
QPalette palette;
palette.setColor(QPalette::Window, QColor(240, 240, 240));
setPalette(palette);
setStyleSheet(QString::fromUtf8("QMainWindow { border: 1px solid #ccc; }"));
}
void MainWindow::paintEvent(QPaintEvent *event)
{
// 绘制边框和标题栏
Q_UNUSED(event);
QPainter painter(this);
painter.setPen(QColor("#ccc"));
painter.drawLine(QPoint(0, 0), QPoint(0, height()));
painter.drawLine(QPoint(0, 0), QPoint(width(), 0));
painter.drawLine(QPoint(0, height() - 1), QPoint(width(), height() - 1));
painter.drawLine(QPoint(width() - 1, 0), QPoint(width() - 1, height()));
painter.drawRect(QRect(0, 0, width() - 1, height() - 1));
painter.setBrush(QColor("#f5f5f5"));
painter.drawRect(QRect(1, 1, width() - 2, 28));
// 绘制标题
painter.setFont(QFont("Microsoft Yahei", 12));
painter.setPen(QColor("#333"));
painter.drawText(QRect(10, 5, width() - 20, 20), Qt::AlignLeft | Qt::AlignVCenter, windowTitle());
}
```
2. 通过鼠标更改窗口大小
可以在QT的main.cpp文件中添加以下代码,实现通过鼠标拖动窗口边框改变窗口大小的功能。具体实现可以在QWindows类中重写mousePressEvent、mouseMoveEvent和mouseReleaseEvent三个方法,以实现鼠标移动时改变窗口大小的效果。
```c++
#include <windows.h>
#include <windowsx.h>
void mousePressEvent(QMouseEvent *event)
{
if (event->button() == Qt::LeftButton)
{
HWND hWnd = HWND(winId());
if (hWnd)
{
int xPos = GET_X_LPARAM(event->globalPos().x());
int yPos = GET_Y_LPARAM(event->globalPos().y());
POINT pt = { xPos, yPos };
ScreenToClient(hWnd, &pt);
SetCapture(hWnd);
SendMessage(hWnd, WM_NCLBUTTONDOWN, HTBOTTOMRIGHT, MAKELPARAM(pt.x, pt.y));
}
}
}
void mouseMoveEvent(QMouseEvent *event)
{
HWND hWnd = HWND(winId());
if (hWnd && (GetCapture() == hWnd))
{
int xPos = GET_X_LPARAM(event->globalPos().x());
int yPos = GET_Y_LPARAM(event->globalPos().y());
POINT pt = { xPos, yPos };
ScreenToClient(hWnd, &pt);
SendMessage(hWnd, WM_NCLBUTTONDOWN, HTBOTTOMRIGHT, MAKELPARAM(pt.x, pt.y));
}
}
void mouseReleaseEvent(QMouseEvent *event)
{
if (event->button() == Qt::LeftButton)
{
HWND hWnd = HWND(winId());
if (hWnd && (GetCapture() == hWnd))
{
ReleaseCapture();
}
}
}
```
阅读全文