Qt- Как получить цвет QPoint в QImage для QPixmap

Я пытаюсь реализовать алгоритм заливки, который требует на каждой итерации, чтобы получить цвет точки в области. Но цвет выбранной точки всегда является цветом фона, даже если я что-то нарисовал.

void MainWindow::floodFill(QPainter& p, int x, int y, const QColor& cu, const QColor& cc) {

   st.push(QPair<int, int>(x, y)); 

   //used for debug
   int _r, _g, _b;
   int _rCu, _gCu, _bCu;
   int _rCc, _gCc, _bCc; 
   cu.getRgb(&_rCu, &_gCu, &_bCu);
   cc.getRgb(&_rCc, &_gCc, &_bCc);

   while (!st.isEmpty()) {
      QPair<int, int> pair = st.pop();
      QPixmap qPix = ui->centralWidget->grab();
      QImage image(qPix.toImage());
      QColor c(image.pixel(pair.first, pair.second));

      //used for debug, here QColor c is always the same
      c.getRgb(&_r, &_g, &_b);

      if (c == cu || c == cc) {
         continue;
      }
      p.setPen(cu);
      p.drawPoint(pair.first, pair.second);


      if (pair.first > 0) {
         st.push(QPair<int, int>(pair.first - 1, pair.second));
      }
      if (pair.first < 200/*ui->centralWidget->width()*/) {
         st.push(QPair<int, int>(pair.first + 1, pair.second));
      }
      if (pair.second > 0) {
         st.push(QPair<int, int>(pair.first, pair.second - 1));
      }
      if (pair.second < 200/*ui->centralWidget->height()*/) {
         st.push(QPair<int, int>(pair.first, pair.second + 1));
      }
   }
}

это то, что я называю в событии краски

void MainWindow::paintEvent(QPaintEvent* event) {
   QPainter p(this);
   QColor colorRed(255, 0, 0);
   QColor colorBlack(0, 0, 0);

   p.setPen(QPen(colorBlack));

   p.drawRect(50, 50, 3, 3);


   floodFill(p, 51, 51, colorRed, colorBlack);
}

1 ответ

Я думаю, что проблема заключается в следующем: вы захватываете центральный виджет в изображение, но рисуете в другом устройстве рисования (само главное окно). Я бы не стал звонить grab в каждом paintEvent позвоните, но вы можете попробовать использовать render чтобы получить изображение, вот так:

QPixmap qPix(size());
render(&qPix);
QImage image(qPix.toImage());

Обратите внимание, что вы, скорее всего, получите предупреждение во время выполнения от Qt (Recursive repaint detected), но только один раз. С помощью grab должно привести к бесконечной рекурсии.

Другие вопросы по тегам