2011-12-21 30 views
5

中心点を中心に矩形を回転させ、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)); 

} 

答えて

9
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()で行われた変換をリセットすることができます。

+3

私は思う*私は今起こっていることを理解しています。画家は何でも0,0から始まります。 100,100に変換するとPainterはまだ0,0で始まりますが、新しい0,0は100,100になります。 –

関連する問題