QPainter::begin: Paint device returned engine == 0, type: 2 解决方法,在使用第三方库Qt可视化节点编辑器时

QT节点编辑器:https://github.com/paceholder/nodeeditor
在使用的时候,沿着对角线缩放节点会出现崩溃的情况
报出来的错误却是:Qt begin: Paint device returned engine == 0, type 2
先看看
Qt提示QPainter::begin: Paint device returned engine == 0, type:0/1/2/3…,type数值代表什么

class Q_CORE_EXPORT QInternal {
public:
    enum PaintDeviceFlags {
        UnknownDevice = 0x00,
        Widget        = 0x01,
        Pixmap        = 0x02,
        Image         = 0x03,
        Printer       = 0x04,
        Picture       = 0x05,
        Pbuffer       = 0x06,    // GL pbuffer
        FramebufferObject = 0x07, // GL framebuffer object
        CustomRaster  = 0x08,
        MacQuartz     = 0x09,
        PaintBuffer   = 0x0a,
        OpenGL        = 0x0b
    };

0x02代表了Pixmap,0x03代表了Image,应该是绘制这些图片的时候出的问题。
发现的问题是在NodeGeometry.cpp中的widgetPosition()函数中的问题,
在计算坐标点的时候,原来的代码usigned和int混用,造成了int被转换成unsinged int,当结果本来应该为负数的时候,就变成了一个很大的整数,造成奔溃的。

NodeGeometry.cpp中

QPointF
NodeGeometry::
widgetPosition() const
{
  if (auto w = _dataModel->embeddedWidget())
  {
    if (_dataModel->validationState() != NodeValidationState::Valid)
    {
      return QPointF(_spacing + portWidth(PortType::In),
                     (captionHeight() + _height - validationHeight() - _spacing - w->height()) / 2.0);
    }

    return QPointF(_spacing + portWidth(PortType::In),
                   (captionHeight() + _height - w->height()) / 2.0);
  }

  return QPointF();
}

调用这个函数的地方是:

void
NodeGraphicsObject::
mouseMoveEvent(QGraphicsSceneMouseEvent * event)
{
  auto & geom  = _node.nodeGeometry();
  auto & state = _node.nodeState();

  if (state.resizing())
  {
    auto diff = event->pos() - event->lastPos();

    if (auto w = _node.nodeDataModel()->embeddedWidget())
    {
      prepareGeometryChange();

      auto oldSize = w->size();

      oldSize += QSize(diff.x(), diff.y());

      w->setFixedSize(oldSize);

      _proxyWidget->setMinimumSize(oldSize);
      _proxyWidget->setMaximumSize(oldSize);
      _proxyWidget->setPos(geom.widgetPosition());//这里调用了widgetPosition函数

      geom.recalculateSize();
      update();

      moveConnections();

      event->accept();
    }
  }
 ...
}

captionHeight()是unsigned int, _height也是unsigned int, w->height()是int,由此的教训是:千万别混用无符号和有符号的数进行运算。

C++中有符号类型(int)和无符号类型(unsigned int)混合算术运算的类型转换会出现的问题
https://blog.csdn.net/xingkongfenqi/article/details/49704521

参考:
Qt/C++ QPainter::pen: Painter not active (QPainter::begin: Paint device returned engine == 0, type: 1)
https://stackoverflow.com/questions/17568941/qt-c-qpainterpen-painter-not-active-qpainterbegin-paint-device-returned

QPainter::begin: Paint device returned engine == 0, type: 2 解决方法
https://blog.csdn.net/lovelyloulou/article/details/7179513

这个没试过:
http://www.itdaan.com/blog/2016/10/29/9718254b7df908e7b240ccf0aa655762.html

你可能感兴趣的:(QT)