c++ - 围绕其中心旋转矩形

标签 c++ qt

我需要围绕它的中心点旋转一个矩形并将其显示在 QWidget 的中心。你能完成这个特定的代码吗?如果可能,您是否也可以简化解释或提供指向最简单解释的链接?

请注意:我已经阅读了 Qt 文档,编译了处理旋转的示例/演示,但我仍然无法理解它!

void Canvas::paintEvent(QPaintEvent *event)
{
    QPainter paint(this);

    paint.setBrush(Qt::transparent);
    paint.setPen(Qt::black);
    paint.drawLine(this->width()/2, 0, this->width()/2, this->height());
    paint.drawLine(0, this->height()/2, this->width(), this->height()/2);

    paint.setBrush(Qt::white);
    paint.setPen(Qt::blue);

    // Draw a 13x17 rectangle rotated to 45 degrees around its center-point
    // in the center of the canvas.

    paint.drawRect(QRect(0,0, 13, 17));

}

最佳答案

 void paintEvent(QPaintEvent* event){
    QPainter painter(this);

    // xc and yc are the center of the widget's rect.
    qreal xc = width() * 0.5;
    qreal yc = height() * 0.5;

    painter.setPen(Qt::black);

    // draw the cross lines.
    painter.drawLine(xc, rect().top(), xc, rect().bottom());
    painter.drawLine(rect().left(), yc, rect().right(), yc);

    painter.setBrush(Qt::white);
    painter.setPen(Qt::blue);

    // Draw a 13x17 rectangle rotated to 45 degrees around its center-point
    // in the center of the canvas.

    // translates the coordinate system by xc and yc
    painter.translate(xc, yc);

    // then rotate the coordinate system by 45 degrees
    painter.rotate(45);

    // we need to move the rectangle that we draw by rx and ry so it's in the center.
    qreal rx = -(13 * 0.5);
    qreal ry = -(17 * 0.5);
    painter.drawRect(QRect(rx, ry, 13, 17));
  }

你在画家的坐标系中。当您调用 drawRect(x, y, 13, 17) 时,它的左上角位于 (x,y)。如果你想让 (x, y) 成为矩形的中心,那么你需要将矩形移动一半,因此 rxry.

您可以调用 resetTransform() 来重置由 translate()rotate() 进行的转换。

关于c++ - 围绕其中心旋转矩形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8586088/

相关文章:

java - Java 数组与 C++ 数组的性能和内存使用情况

python - PyQt4:信号槽机制无法正常工作 'List of buttons'

c++ - 打印最大的单精度 float

c++ - 来自模板化基类的派生类

c++ - 在 C++ 中用枚举类型包装 C-API

c++从列表中删除对象 - 不起作用

c++ - 是否有免费的 C++ xsl-fo 转 PDF 引擎?

performance - QOpenGLWindow 和 QOpenGLWidget 之间的性能差异是什么?

c++ - Qt:QSS 和 drawComplexControl()

c++ - Qt DBus 监视器方法调用