2011-12-21 17 views
5

मुझे इसके केंद्र बिंदु के चारों ओर एक आयताकार घुमाने और इसे QWidget के केंद्र में प्रदर्शित करने की आवश्यकता है। क्या आप इस विशिष्ट कोड को पूरा कर सकते हैं? यदि संभव हो, तो क्या आप व्याख्या को कम कर सकते हैं या सरल व्याख्या के लिए एक लिंक प्रदान कर सकते हैं?अपने केंद्र के चारों ओर आयत घुमाएं

कृपया ध्यान दें: मैंने क्यूटी दस्तावेज, संकलित उदाहरण/डेमो को पढ़ा है जो घूर्णन से निपटते हैं और मैं अभी भी इसे समझ नहीं सकता!

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) चाहते हैं, तो आपको आयत को आधे से स्थानांतरित करने की आवश्यकता है, इसलिए rx और ry

translate() और rotate() द्वारा किए गए परिवर्तनों को रीसेट करने के लिए आप resetTransform() पर कॉल कर सकते हैं।

+3

मुझे लगता है * मैं समझता हूं कि अब क्या हो रहा है। पेंटर हमेशा 0,0 से शुरू होता है इससे कोई फर्क नहीं पड़ता। तो जब आप 100,100 पेंटर में अनुवाद करते हैं तो अभी भी 0,0 से शुरू होता है लेकिन नया 0,0 अब 100,100 होता है? –

संबंधित मुद्दे