【问题标题】:How to retrieve the QPainter object in QML Canvas object如何在 QML Canvas 对象中检索 QPainter 对象
【发布时间】:2021-07-21 16:47:37
【问题描述】:

我有一个 QML 画布,通过覆盖 paint(QPainter *painter) 方法并使用一堆使用该 painter 对象的语句,我在 C++ 中绘图。

类似...

void myGraphDisplay::paint (QPainter* painter) {

    QPainterPath path;
    path.MoveTo(0, 0);
    path.LineTo(100, 100);
    painter->strokePath(path, painter->pen());

等等

现在一段时间后,另一个函数想要在画布上绘图,但 painter 对象不再可用。我尝试将其保存为 myGraphDisplay 类的私有成员,但如果我尝试在稍后的函数中再次访问它,我的应用程序将崩溃。

void myGraphDisplay::updateGraph () {
    QPainterPath path;
    path.MoveTo(100, 0);
    path.LineTo(0, 100);
    painter->strokePath(path, painter->pen()); // where do I get "painter" here?

我也试过

QPainter painter(this);

QT reference pages 所示,但这给了我一个错误...

没有匹配的函数调用 QPainter::QPainter(myGraphDisplay*)

如何获取当前的QPainter 对象?如果有任何帮助,updateGraph() 是从同一 QML 调用的 Q_INVOKABLE

【问题讨论】:

    标签: c++ qt qml


    【解决方案1】:

    规则规定绘制 QQuickItem 的过程发生在paint 方法中,而不是在其他方法中。通用解决方案是:

    1. 将绘画信息保存在类的某个属性中。
    2. 调用绘制方法
    3. 在paint方法中实现逻辑。

    *.h

    private:
        QPainterPath m_path;
    

    *.cpp

    myGraphDisplay::myGraphDisplay(QQuickItem *parent): QQuickItem(parent){
        // default path
        m_path.MoveTo(0, 0);
        m_path.LineTo(100, 100);
    }
    
    void myGraphDisplay::updateGraph(){
        QPainterPath path;
        path.MoveTo(100, 0);
        path.LineTo(0, 100);
        m_path = path;
        update();
    }
    
    void myGraphDisplay::paint (QPainter* painter) {
        painter->strokePath(m_path, painter->pen());
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-13
      • 1970-01-01
      相关资源
      最近更新 更多