Login

Grabbing all QGraphicItems current viewable in a QGraphicView

The best way to get a list of all items current displayed inside the QGraphicsView is done through the combination of three steps:

  1. get viewing rectangle
  2. get items intersecting or inside rectangle
  3. check for visibility
    1
    2
    3
    4
    5
    6
    7
    
    QList<QGraphicsItem* > viewItems = m_pView->items(m_pView->rect());
     
    for(int i=0; i < viewItems.size(); ++i) {
    	if(viewItems.at(i)->isVisible()) {
    		//payload
    	}
    }

    Do not use other rectangle functions like sceneRect(), childrenRect(), contentsRect(), etc… as they will not give you the correct bounding region. Also this operation returns all items, so one must check for visibility manually and cast points to any derived class as appropriate.

    With casting

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    
    QList<QGraphicsItem* > viewItems = m_pView->items(m_pView->rect());
    NewType *newType;
     
    for(int i=0; i < viewItems.size(); ++i) {
    	if(viewItems.at(i)->isVisible()) {
    		newType = dynamic_cast<NewType *> (viewItems[i]);
    		if(newType != NULL) {
    			//payload
    		}
    	}
    }

    Related posts:

    1. Making a QPixmap transparent the Right Way
    This entry was posted in Qt Code and tagged , , , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

    Post a Comment

    Your email is never published nor shared. Required fields are marked *

    *
    *

    You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">