Get just lines items from a scene where there are some kind of items.



  • Hello everyone.
    First of all thanks a lot for helping me and reading this post.

    i have a scene where tehera are lines items and a pixmap item.
    Then I would like to move just the lines items (not the pixmap item).
    My code is like this:

            QList<QGraphicsItem*>a;
            a = scene->items();
    
        for (int i=0; i<a.size();i++){
    
            QGraphicsItem* my_item = a.value(i); //Item (i) selected
            QGraphicsLineItem *line_at = qgraphicsitem_cast<QGraphicsLineItem *>(my_item);
    
            double XStart_line=line_at->line().x1(); //X_start of line i.
            double XEnd_line=line_at->line().x2();
            double YStart_line=line_at->line().y1();
            double YEnd_line=line_at->line().y2();
    
    ..... //move the item i
    

    It does not give me any errors but when I run this code fragment it gives me this:
    The program has unexpectedly finished.

    I think that the problem is that when I run this code I am trying to move every kind of items, not just line items so for that reason it gives me an error.

    How can I get information just for Lines items┬┐?
    Because if I get to move just the lines items in FOR it will be solved I think.

    Thanks a lot!


  • Moderators

    You should check line_at: is it null or not?
    See here: http://doc.qt.io/qt-5/qgraphicsitem.html#qgraphicsitem_cast

    QGraphicsLineItem *line_at = qgraphicsitem_cast<QGraphicsLineItem *>(my_item);
    

    If my_item is not QGraphicsLineItem qgraphicsitem_cast will return null and then you dereference null pointer and your program crashes.



  • @jsulm It is QGraphics line item just in Lines items.. not in Pixmap... so when iteration FOR is the pixmap iteration, it is crashed... so how can I get just lines items from a scene?


  • Moderators

    As I said just check the pointer:

    QList<QGraphicsItem*>a;
    a = scene->items();
    for (int i=0; i<a.size();i++){
        QGraphicsItem* my_item = a.value(i); //Item (i) selected
        QGraphicsLineItem *line_at = qgraphicsitem_cast<QGraphicsLineItem *>(my_item);
        if (line_at == nullptr)
            continue; // my_item is not a line
    
       double XStart_line=line_at->line().x1(); //X_start of line i.
       double XEnd_line=line_at->line().x2();
       double YStart_line=line_at->line().y1();
       double YEnd_line=line_at->line().y2();
    
    ..... //move the item i
    


  • @jsulm Thanks a lot my friend!!!! That works!!


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.