5

我有:

class QTextEditEnter : public QTextEdit
{
    Q_OBJECT
public:
    QTextEditEnter( QWidget *_parent ) : QTextEdit(_parent)
    {
        this -> setFrameStyle( QFrame::Sunken ); // Sunken!
    }

protected:
    virtual void keyPressEvent(QKeyEvent * event);
    virtual void paintEvent(QPaintEvent *_event)
    {
        QTextEdit::paintEvent( _event );
        QPainter pnt(this);
        pnt.setPen( QColor( 0, 0, 0, 0xff ));
        pnt.drawRect( 0, 0, width(), height());
    }

    signals:
        void signalPressEnter();
};

这给出了:

QPainter::begin: Widget painting can only begin as a result of a paintEvent
QPainter::setPen: Painter not active
QPainter::drawRects: Painter not active
QPainter::begin: Widget painting can only begin as a result of a paintEvent
QPainter::setPen: Painter not active
QPainter::drawRects: Painter not active

为什么会这样?

更新

// QPainter( this )
// QTextEdit::paintEvent at the begining of custom PaintEvent
// RESULT: "QPainter::begin: Widget painting can only begin as a result of a paintEvent" ...
virtual void paintEvent(QPaintEvent *_event)
{
    QTextEdit::paintEvent( _event );
    QPainter pnt( this );
    pnt.setPen( QColor( 0, 0, 0, 0xff ));
    pnt.drawRect( 0, 0, width()-1, height()-1);
}

// QPainter ( viewport() )
// QTextEdit::paintEvent at the begining of custom PaintEvent
// RESULT: works.
virtual void paintEvent(QPaintEvent *_event)
{
    QTextEdit::paintEvent( _event );
    QPainter pnt( viewport() );
    pnt.setPen( QColor( 0, 0, 0, 0xff ));
    pnt.drawRect( 0, 0, width()-1, height()-1);
}

// *** BONUS ***
// QPainter( viewport() ) or QPainter ( this )
// QTextEdit::paintEvent after QPainter() constructor.
// RESULT: Segmentation fault.
virtual void paintEvent(QPaintEvent *_event)
{
    QPainter pnt( viewport() );
    pnt.setPen( QColor( 0, 0, 0, 0xff ));
    QTextEdit::paintEvent( _event ); // WRONG PLACE!!!
    pnt.drawRect( 0, 0, width()-1, height()-1);
}
4

1 回答 1

8

代替

QPainter pnt(this);

尝试

QPainter pnt(viewport());
pnt.setPen(QColor( 0, 0, 0, 0xff ));
pnt.drawRect(viewport()->rect());

viewport() 是可绘制区域,可能是导致问题的原因

于 2012-11-23T15:13:43.693 回答