Qt how to create bitmap from data from QVector and show it on widget?

1.9k views Asked by At

I'm wondering how I can create bitmap from my data and show it on my widget.

I have QVector vector, which is vector of some points to draw chart. How I can repaint it on my widget but with using QBitmap? I don't want draw simply on widget, I prefer pass the pixmap to widget, just to show it.

How can I do this?

My code:

QPainter painter(pixMap);
painter.setPen(QPen(Qt::black, 2));
painter.drawPolyline(this->data.data(), this->data.size());
painter.drawLine(QPointF(5,5),QPointF(50,50));

setPixmap(*pixMap);

Here is my sample code. Why it's not working? I can't see anything on widget.

enter image description here

I have widget class

class Widget : public QLabel
{
  public:
    Widget(QVector<QPointF> * data);
    ~Widget();
  protected:
    void paintEvent(QPaintEvent * event);
  private:
    QVector<QPointF> data;
    QPixmap *pixMap;
};

In constructor I have

 Widget::Widget(QVector<QPointF> * data){
   pixMap = new QPixmap(300,300);
   pixMap->fill(Qt::red);
 }

And in paintEvent

void Waveform::paintEvent(QPaintEvent *event)
{
  QPainter painter(pixMap);
  painter.setPen(QPen(Qt::white, 2));
  painter.drawPolyline(this->data.data(), this->data.size());
  painter.drawLine(QPointF(5,5),QPointF(50,50));
  setPixmap(*pixMap);
}

If I replace QPainter painter(pixMap) with QPainter painter(this), I can see my chart. But I want to use pixmap.

1

There are 1 answers

5
Jablonski On BEST ANSWER

I think so, but I wasn't sure without full code, now I am absolutely sure. You should do standard processing of paintEvent. So try this:

void Waveform::paintEvent(QPaintEvent *e)
{
    static const QPointF points[3] = {
        QPointF(10.0, 80.0),
        QPointF(20.0, 10.0),
        QPointF(80.0, 30.0),
    };
    QPainter painter(pixMap);
    painter.setPen(QPen(Qt::black, 2));
    painter.drawPolyline(points, 3);
    painter.drawLine(QPointF(5,5),QPointF(50,50));
    setPixmap(*pixMap);
    QLabel::paintEvent(e);//standard processing
}

But I think that you don't need paintEvent at all, then you can totally remove paintEvent from your class or do

void VertLabel::paintEvent(QPaintEvent *e)
{
    QLabel::paintEvent(e);//in this case you don't need paintEvent at all, remove it from cpp and header files
}

and in constructor:

   pixMap = new QPixmap(300,300);
   pixMap->fill(Qt::red);
   this->resize(300,300);
   static const QPointF points[3] = {
       QPointF(10.0, 80.0),
       QPointF(20.0, 10.0),
       QPointF(80.0, 30.0),
   };
   QPainter painter(pixMap);
   painter.setPen(QPen(Qt::black, 2));
   painter.drawPolyline(points, 3);
   painter.drawLine(QPointF(5,5),QPointF(50,50));
   setPixmap(*pixMap);