qt 旋转矩形,鼠标拉伸矩形框变形了
时间: 2023-08-19 07:15:33 浏览: 100
鼠标勾画矩形框改变大小
在Qt中旋转矩形可以使用QTransform类。为了在旋转后保持矩形的形状,您需要使用`QPainter::setWorldTransform()`方法将变换应用于绘制操作。然后,您可以使用鼠标事件来实现拖拽和拉伸矩形的功能。
下面是一个示例代码,展示了如何旋转矩形并实现拖拽和拉伸矩形的功能:
```cpp
#include <QtWidgets>
class MyWidget : public QWidget
{
public:
MyWidget(QWidget *parent = nullptr)
: QWidget(parent)
{
setMouseTracking(true);
setFixedSize(400, 400);
m_rect = QRect(100, 100, 100, 50);
m_rotation = 0;
}
protected:
void paintEvent(QPaintEvent *) override
{
QPainter painter(this);
painter.setRenderHint(QPainter::Antialiasing);
painter.save();
painter.translate(m_rect.center());
painter.rotate(m_rotation);
painter.drawRect(-m_rect.width() / 2, -m_rect.height() / 2, m_rect.width(), m_rect.height());
painter.restore();
}
void mousePressEvent(QMouseEvent *event) override
{
if (event->button() == Qt::LeftButton)
{
m_dragStartPosition = event->pos();
m_dragging = true;
}
}
void mouseMoveEvent(QMouseEvent *event) override
{
if (m_dragging)
{
QPoint diff = event->pos() - m_dragStartPosition;
m_rect.translate(diff);
m_dragStartPosition = event->pos();
update();
}
else
{
QRect top = QRect(m_rect.x() + m_rect.width() / 4, m_rect.y() - 2, m_rect.width() / 2, 4);
QRect bottom = QRect(m_rect.x() + m_rect.width() / 4, m_rect.y() + m_rect.height() - 2, m_rect.width() / 2, 4);
QRect left = QRect(m_rect.x() - 2, m_rect.y() + m_rect.height() / 4, 4, m_rect.height() / 2);
QRect right = QRect(m_rect.x() + m_rect.width() - 2, m_rect.y() + m_rect.height() / 4, 4, m_rect.height() / 2);
if (top.contains(event->pos()))
{
setCursor(Qt::SizeVerCursor);
}
else if (bottom.contains(event->pos()))
{
setCursor(Qt::SizeVerCursor);
}
else if (left.contains(event->pos()))
{
setCursor(Qt::SizeHorCursor);
}
else if (right.contains(event->pos()))
{
setCursor(Qt::SizeHorCursor);
}
else
{
setCursor(Qt::ArrowCursor);
}
}
}
void mouseReleaseEvent(QMouseEvent *event) override
{
Q_UNUSED(event);
m_dragging = false;
}
void mouseDoubleClickEvent(QMouseEvent *event) override
{
Q_UNUSED(event);
m_rotation += 20;
update();
}
void resizeEvent(QResizeEvent *) override
{
m_rect.moveCenter(rect().center());
}
private:
QRect m_rect;
int m_rotation;
QPoint m_dragStartPosition;
bool m_dragging;
};
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MyWidget w;
w.show();
return a.exec();
}
```
此示例中,我们使用`QPainter::setWorldTransform()`方法将变换应用于绘制操作。我们还使用鼠标事件来实现拖拽和拉伸矩形的功能。在`mouseMoveEvent()`方法中,我们检查鼠标位置是否在矩形的边缘,并相应地更改光标形状。在`mouseDoubleClickEvent()`方法中,我们旋转矩形20度。
阅读全文