Getting screen coordinates of QGraphicsItem, QGraphicsObject

Last edited on

JavaScript:

function main()
{
    //...

    var name_view = "{type='QGraphicsView'}";
    var name_item = "{acceptDrops='yes' container=':Drag and Drop Robot_QGraphicsObject' enabled='yes' focusable='no' movable='no' selectable='no' type='QGraphicsObject' visible='yes'}";
    rect = qgraphicsitem_to_display_coordinates(name_view, name_item)
    test.log(rect.x + " / " + rect.y);

    //...
}

function qgraphicsitem_to_display_coordinates(viewObjectOrName, itemObjectOrName)
{
    var get_pos = function(view, item, point) {
            var scenePos = item.mapToScene(point);
            var viewportPos = view.mapFromScene(scenePos);
            var viewPos = view.viewport().mapToParent(viewportPos);
            var globalViewPos = view.mapToGlobal(new QPoint(0, 0));
            return [globalViewPos.x + viewPos.x, globalViewPos.y + viewPos.y];
        }

    var item = waitForObject(itemObjectOrName);
    if (typeName(item) != "QGraphicsItem") {
        item = object.convertTo(item, "QGraphicsItem");
    }
    var view = waitForObject(viewObjectOrName);
    var itemRect = item.boundingRect();
    var r = new Object();
    var p = get_pos(view, item, itemRect.topLeft());
    r.x = p[0];
    r.y = p[1];
    p = get_pos(view, item, itemRect.bottomRight());
    r.x2 = p[0];
    r.y2 = p[1];
    r.width = r.x2 - r.x;
    r.height = r.y2 - r.y;
    return r;
}
test.js

Python:

def main():
    #...

    name_view = "{type='QGraphicsView'}"
    name_item = "{acceptDrops='yes' container=':Drag and Drop Robot_QGraphicsObject' enabled='yes' focusable='no' movable='no' selectable='no' type='QGraphicsObject' visible='yes'}"

    rect = qgraphicsitem_to_display_coordinates(name_view, name_item)
    test.log("%s / %s" % (rect.x, rect.y))

    #...

def qgraphicsitem_to_display_coordinates(viewObjectOrName, itemObjectOrName):
    class rect:
        pass

    def get_pos(view, item, point):
        scenePos = item.mapToScene(point)
        viewportPos = view.mapFromScene(scenePos)
        viewPos = view.viewport().mapToParent(viewportPos)
        globalViewPos = view.mapToGlobal(QPoint(0, 0))
        return globalViewPos.x + viewPos.x, globalViewPos.y + viewPos.y

    item = waitForObject(itemObjectOrName)
    if className(item) != "QGraphicsItem":
        item = object.convertTo(item, "QGraphicsItem")
    view = waitForObject(viewObjectOrName)
    itemRect = item.boundingRect()
    r = rect()
    r.x, r.y = get_pos(view, item, itemRect.topLeft())
    r.x2, r.y2 = get_pos(view, item, itemRect.bottomRight())
    r.width = r.x2 - r.x
    r.height = r.y2 - r.y    
    return r
test.py