在QGraphicsView上的第一个和最后一个QPoint之间绘制一条线



我有一个类,允许用户通过单击图像上的任何位置来创建自动相互连接的点,从而在图像上绘制一条连续的线。

GraphicsScene::GraphicsScene(QObject *parent) :
    QGraphicsScene(parent){
    //...
    qimOriginal = QImage((uchar*)src.data, src.cols, src.rows, src.step, QImage::Format_RGB888);
    addPixmap(QPixmap::fromImage(qimOriginal));
}
void GraphicsScene::mousePressEvent(QGraphicsSceneMouseEvent *mouseEvent){
    if (mouseEvent->button() == Qt::LeftButton){
        QPoint pos = mouseEvent->scenePos().toPoint();
        pol.append(pos);
        if(pol.size() > 1){
            QPainterPath myPath;
            myPath.addPolygon(pol);
            addPath(myPath,QPen(Qt::red,1));
        }
    }
}

在使用GraphicsScene的对话框窗口中,我有一个按钮,单击该按钮可返回GraphicsScene的矢量和点的坐标。在它返回向量之前,我想在QPolygon的第一个点和最后一个点之间画一条线来创建一个区域。以下是我的GraphicsScene::getCoordinates()函数:

std::vector<Point2f> GraphicsScene::getCoordinates(){
    qDebug() << pol.first() << pol.last();
    addLine(QLine(pol.first(),pol.last()),QPen(Qt::red,1));
    std::vector<Point2f> vecPoint;
    if (pol.size()>2){
        std::vector<QPoint> myVec = pol.toStdVector();
        for(int i=0; i<myVec.size(); i++) {
            QPoint point = myVec[i];
            Point2f p(point.x(), point.y());
            vecPoint.push_back(p);
        }
        pol.clear();
        this->clear();
        return vecPoint;
    }
    else{
         cout << "empty vector" << endl;
         return vecPoint;
    }
}

我的问题是,由于某种原因,addLine(QLine(pol.first(),pol.last()),QPen(Qt::red,1));没有在我的图像上绘制任何内容。

正如您所说:

 I did have QThread::sleep(1); after the addLine()

相信我,这就是你们问题的根源。QThread::sleep(1);休眠,但这并不意味着您的更改(您的addLine)显示在屏幕上,不!

这个代码,你知道,从我的一个答案中,它现在没有添加行,它等待1秒,之后你可以看到这行。这是线程问题。

if(pol.size() > 1){
    QPainterPath myPath;
    myPath.addPolygon(pol);
    addPath(myPath,QPen(Qt::red,1));
    qDebug() << pol.first() << pol.last();
    addLine(QLine(pol.first(),pol.last()),QPen(Qt::red,1));
    Sleep(1000);//Sleep from WinApi
}

这是你问题的根源,但如何解决?这是另一个问题,但我可以建议你尝试使用

QTimer::singleShot(1000,this,SLOT(echo()));

在插槽中,你应该清除你的场景,当然你应该删除

QThread::sleep(1);

从您的代码。

最新更新