2016-06-23 37 views
1

質問: GraphicsViewのpaintEventを呼び出すことができません。つまり、QPainterを完全に動作させる方法がわかりません。QGraphicsViewサブクラスを使用してQPainterで線を描く

  • qtcreatorのデザイナを使用してQGraphicsViewをメインウィンドウに配置しています。
  • Iサブ分類QGraphicsView(class DrawpaintEventをオーバーライドし、メインウィンドウにこのサブクラス(Draw draw)のインスタンスを保持する(Iは、他の場所で複雑な図面を移動したかった)
  • Iはnew QGraphicsSceneを作成し、両方に割り当てますQGraphicsView'sui->graphicsViewdraw)ですので、Drawの中に描画すると、
    ui->graphicsviewでも同様に表示されます(願っています)。
  • 新しいsceneオブジェクトを使用して描画すると、私は目に見える結果が得られることを確信しています(ただし、sceneオブジェクトを描画に使用するのではなく、QPainterオブジェクトを使用します)。したがって、私はQGraphicsViewをサブクラス化してpaintEventをオーバーライドして、QPainter p(this)を簡単に取得しようとしています。
  • イベントが発生したときDrawオブジェクトでpaintEvent()を呼び出しようとしているWindow.cppMyRepaint()を呼び出しますが、動作しません。

メインウィンドウのWindow.cpp ':

QGraphicsViewをサブクラス
Window::Window(QWidget* parent) : 
    QMainWindow(parent), 
    ui(new Ui::Window), 
    draw(*this) //my own QGraphicsView instance (see class below) 
{ 
    ui->setupUi(this); 
    //assigning a new scene to draw and to window's graphicsView 
    this->scene = new QGraphicsScene(this); 
    this->draw.setScene(scene); 
    this->ui->graphicsView->setScene(scene); 
} 

void Window::MyRepaint() 
{ 
    qInfo() << "Repaint - start" << this->draw.scene(); 
    this->draw.scene()->update(this->draw.sceneRect()); 
    this->draw.repaint(); 
    this->draw.viewport()->update(); 
    /*only the following line made the paintEvent executed eventually but without a visible result and with an error in the output*/ 
    this->draw.paintEvent(NULL); 
    qInfo() << "Repaint - end"; 
} 

、ファイル:Draw.h:

class Window; 
class Draw : public QGraphicsView{ 
private: 
    Window& parent; 

public: 
    Draw(Window &parent); 
    void paintEvent(QPaintEvent*e) override; 
}; 

Draw.cpp

void Draw::paintEvent(QPaintEvent *e) 
{ 
    qInfo() << "trying to draw"; 
    QPainter p(this); 
    p.setPen(QPen(Qt::black, 12, Qt::DashDotLine, Qt::RoundCap)); 
    p.drawLine(0, 0, 200, 200); 
} 

出力:

Repaint - start QGraphicsScene(0x15c7eca8) 
trying to draw 
QWidget::paintEngine: Should no longer be called 
QPainter::begin: Paint device returned engine == 0, type: 1 
QPainter::setPen: Painter not active 
QPainter::viewport: Painter not active 
QPainter::end: Painter not active, aborted 
Repaint - end 

多分私は完全に間違ったアプローチを選択しました。

答えて

3

QGraphicsViewはQGraphicsSceneで動作するように設計されています。線を描画したいだけなら、QWidgetから派生し、paintEventをオーバーライドします。設計者はQWidgetを派生クラスに昇格させます。

また、Qtには適切な文書があります。 thisページをご覧ください。

+0

はい私はそのページを尋ねました。そのページは、不必要に長すぎる記事です。最小限の例とチュートリアルが必要です。今私はあなたが言及した "プロモーションの事"を見ている、私はそれについて知らなかった。 –

+0

https://bitbucket.org/K117/qtlineexample/src私が書くことができる最も簡単な例です。 – K117

+0

プロモーション。デザイナーでウィジェットのRMBをクリックし、[プロモート先]を選択し、派生クラスの名前を入力します。ウィジェットを派生したクラスにウィジェットをプロモートできます。 – K117

関連する問題