QGraphicsScene set item scene position - qt

I have a QGraphicsScene that contains a hierarchy of QGraphicsItems.
Method item.scenePos() returns the scene coordinates of the item.
I'm looking for something like setScenePos() in order to change positions of the items by giving them scene coordinates.
How can I achieve this ?

As the docs says:
QPointF QGraphicsItem::scenePos() const
Returns the item's position in scene coordinates. This is equivalent to calling mapToScene(0, 0).
to get what you want you can do the inverse
# setScenePos(QPointF point)
point = QPointF(xx, yy)
point_item = item.mapFromScene(point)
item.setPos(point_item)

Related

Qt Widget click 2D pos to 3D world coordinate

My Qt widget show the 3D world.
I have the 3D world's Qt3DRender::QCamera
How can I use Qcamera to convert the mouse position in widget to 3D world coordinate?
I tried to use point * .viewMatrix4x4().transposed().inverted() but it is wrong.
You cannot simply convert a 2D click to a 3D coordinate, only to a 3D vector which is a direction vector. You can only obtain a 3D coordinate if you have an object which is underneath the mouse.
In this case, you can use QObjectPicker to obtain the coordinate.
The steps to do so are:
Create the object picker in your scene hierarchy (it's best to create it as a child of the object you want to pick, but I'm not sure if that's necessary)
Attach the object picker as a component to the object you want to pick
Connect the object picker's signal that gets fired when you click the object to a function of yours that gives you the coordinates
You can also check out the manual Qt3D test on GitHub. It's in QML but you should be able to translate it to C++ (if that's what you're programming in).
I know this question is old, but I had the same problem and wanted to go from qt3d window coordinates to 3d space. I hunted around in the qt3d source code and was able to come up with the following. I think it should work as long as you are using the Qt3DWindow from Qt3DExtras and no additional Viewports.
QVector3D mouseEventToSpace(const QMouseEvent* mouseEvent, const Qt3DRender::QCamera* camera, const QSurface* surface) {
const QPointF glCorrectSurfacePosition{static_cast<float>(mouseEvent->pos().x()),
surface->size().height() - static_cast<float>(mouseEvent->pos().y())};
const QMatrix4x4 viewMatrix{camera->viewMatrix()};
const QMatrix4x4 projectionMatrix{camera->lens()->projectionMatrix()};
const int areaWidth = surface->size().width();
const int areaHeight = surface->size().height();
const auto relativeViewport = QRectF(0.0f, 0.0f, 1.0f, 1.0f);
const auto viewport =
QRect(relativeViewport.x() * areaWidth, (1.0 - relativeViewport.y() - relativeViewport.height()) * areaHeight,
relativeViewport.width() * areaWidth, relativeViewport.height() * areaHeight);
const auto nearPos = QVector3D{static_cast<float>(glCorrectSurfacePosition.x()),
static_cast<float>(glCorrectSurfacePosition.y()), 0.0f}
.unproject(viewMatrix, projectionMatrix, viewport);
return nearPos;}

How to use a QSGSimpleTextureNode?

I'm trying to understand how do I use a QSGSimpleTextureNode but Qt documentation is very vague. I want to render text on the scene graph, so basically what I want is to draw a texture with all the glyphs and then set that texture on a QSGSimpleTextureNode. My idea was to create the texture using standard OpenGL code and set the texture data to the data I have just created. I can't find an example to show me how to achieve this.
I would use QSGGeometryNode instead of QSGSimpleTextureNode. If I am not wrong it is not possible to set the texture coordinates in a QSGSimpleTextureNode. You could write a custom QQuickItem for the SpriteText and override the updatePaintNode:
QSGNode* SpriteText::updatePaintNode(QSGNode *old, UpdatePaintNodeData *data)
{
QSGGeometryNode* node = static_cast<QSGGeometryNode*>(old);
if (!node){
node = new QSGGeometryNode();
}
QSGGeometry *geometry = NULL;
if (!old){
geometry = new QSGGeometry(QSGGeometry::defaultAttributes_TexturedPoint2D()
,vertexCount);
node->setFlag(QSGNode::OwnsGeometry);
node->setMaterial(material); // <-- Texture with your glyphs
node->setFlag(QSGNode::OwnsMaterial);
geometry->setDrawingMode(GL_TRIANGLES);
node->setGeometry(geometry);
} else {
geometry = node->geometry();
geometry->allocate(vertexCount);
}
if (textChanged){
//For every Glyph in Text:
//Calc x + y position for glyph in texture (between 0-1)
//Create vertexes with calculated texture coordinates and calculated x coordinate
geometry->vertexDataAsTexturedPoint2D()[index].set(...);
...
node->markDirty(QSGNode::DirtyGeometry);
}
//you could start timer here which call update() methode
return node;
}

QGraphicsProxyWidget::setPos(qreal x, qreal y) doesn't place correctly in a QGraphicsScene when coordinates > 2^15

I have a QGraphicsScene of big dimension for displaying a database content.
Part of the database is made of pictures that I place in the QGraphicsScene thanks to the method setPos() of a QGraphicsPixmapItem and this works fine with thousands of pictures.
In front of these pictures, I place QCheckboxes that are finally accessible through QGraphicsProxyWidgets. But QGraphicsProxyWidget::setPos(qreal x, qreal y) results in casting provided coordinates in signed short in the QGraphicsScene.
However, doing a QGraphicsProxyWidget::pos() returns correctly the original coordinates, even above 2^16.
Here is the code:
QCheckBox* checkbox = new QCheckBox("", this);
QWidget* dummyWidget = new QWidget; //used for having a transparent background
dummyWidget->setStyleSheet("background-color:transparent;"
"outline-color:transparent;"
"font-size: 8pt;");
QHBoxLayout* dummyLayout = new QHBoxLayout(dummyWidget);
dummyLayout->addWidget(checkbox);
QGraphicsProxyWidget* proxyWidget = scene.addWidget(dummyWidget);
proxyWidget->setPos(0, 120*i);
When 120*i is between 32769 and 65536, QChekBoxes don't show. For above values, QCheckBoxes are shown like if y = value - 65536.
I have tried many things without success, like
- proxyWidget->moveBy
- dummyWidget->move
- dummyWidget->setFixedSize(0, 240*i); checkbox->move(0, 120*i);
Any solution?
PS: The toolchain/cross-toolchain I depend from embeds QT4.8.1. for the desktop side.
I have no way to change that so upgrading to QT5.x is not an option.
You can use next trick:
void setNewPos(QGraphicsItem *item, QPointF pos)
{
item->resetTransform();
QTransform trans = item->transform();
item->setTransform(trans.translate(pos.x(), pos.y()));
}
Now, you can call this func:
QPushButton *btn = new QPushButton("Hello, people!");
QGraphicsProxyWidget *wdgItem = scene->addWidget(btn);
setNewPos(wdgItem, view->mapToScene(0,0)); // There's scenePos can have any coords

How can I get view direction from the OpenGL ModelView Matrix?

I am writing a volume render program that constantly adjusts some plane geometry so it always faces the camera. The plane geometry rotates whenever the camera rotates in order to appear as if it doesn't move--relative to everything else in the scene. (I use the camera's viewing direction as a normal vector to these plane geometries.)
Currently I am manually storing a custom rotation vector ('rotations') and applying its affects as follows in the render function:
gl2.glRotated(rotations.y, 1.0, 0.0, 0.0);
gl2.glRotated(rotations.x, 0.0, 1.0, 0.0);
Then later on I get the viewing direction by rotating the initial view direction (0,0,-1) around the x and y axes with the values from rotation. This is done in the following manner. The final viewing direction is stored in 'view':
public Vec3f getViewingAngle(){
//first rotate the viewing POINT
//then find the vector from there to the center
Vec3f view=new Vec3f(0,0,-1);
float newZ=0;
float ratio=(float) (Math.PI/180);
float vA=(float) (-1f*rotations.y*(ratio));
float hA=(float) (-1f*rotations.x)*ratio;
//rotate about the x axis first
float newY=(float) (view.y*Math.cos(vA)-view.z*Math.sin(vA));
newZ=(float) (view.y*Math.sin(vA)+view.z*Math.cos(vA));
view=new Vec3f(view.x,newY,newZ);
//rotate about Y axis
float newX=(float) (view.z*Math.sin(hA)+view.x*Math.cos(hA));
newZ=(float) (view.z*Math.cos(hA)-view.x*Math.sin(hA));
view=new Vec3f(newX,view.y,newZ);
view=new Vec3f(view.x*-1f,view.y*-1f,view.z*-1f);
//return the finalized normal viewing direction
view=Vec3f.normalized(view);
return view;
}
Now I am moving this program to a larger project wherein the camera rotation is handled by a 3rd party graphics library. I have no rotations vector. Is there some way I can get my view direction vector from:
GLfloat matrix[16];
glGetFloatv (GL_MODELVIEW_MATRIX, matrix);
I am looking at this for reference http://3dengine.org/Modelview_matrix but I still don't get how to come up with the view direction. Can someone explain to me if it is possible and how it works?
You'll want to look at this picture # http://db-in.com/images/local_vectors.jpg
The Direction-of-Flight ( DOF) is the 3rd row.
GLfloat matrix[16];
glGetFloatv( GL_MODELVIEW_MATRIX, matrix );
float DOF[3];
DOF[0] = matrix[ 2 ]; // x
DOF[1] = matrix[ 6 ]; // y
DOF[2] = matrix[ 10 ]; // z
Reference:
http://blog.db-in.com/cameras-on-opengl-es-2-x/
Instead of trying to follow the modelview matrix, to adjust your volume rasterizer's fragment impostor, you should just adjust the modelview matrix to your needs. OpenGL is not a scene graph, it's a drawing system and you can, and should change things however they suit you best.
Of course if you must embedd the volume rasterization into a larger scene, it may be neccessary to extract certain info from the modelview matrix. The upper left 3×3 submatrix contains the composite rotation of models and view. The 3rd column contains the view rotated Z vector.

QGraphicsItem's - selection & rotation

I'd like to implement application which allows user to select few QGraphicsItems and then rotate them as a group. I know that I could add all items into one QGraphicsItemGroup but I need to keep Z-value of each item. Is it possible?
I also have a second question.
I'm trying to rotate QGraphicsItem around some point (different from (0,0) - let's say (200,150)). After that operation I want to rotate this item once more time but now around (0,0). I'm using code below:
QPointF point(200,150); // point is (200,150) at first time and then it is changed to (0,0) - no matter how...
qreal x = temp.rx();
qreal y = temp.ry();
item->setTransform(item->transform()*(QTransform().translate(x,y).rotate(angle).translate(-x,-y)));
I noticed that after second rotation the item is not rotated around point (0,0) but around some other point (I don't know which). I also noticed that if I change order of operations it all works great.
What am I doing wrong?
Regarding your first problem, why should the z-values be a problem when putting them into a QGraphicsGroup?
On the other hand you could also iterate through the selected items and just apply the transformation.
I guess this snippet will solve your 2nd problem:
QGraphicsView view;
QGraphicsScene scene;
QPointF itemPosToRotate(-35,-35);
QPointF pivotPoint(25,25);
QGraphicsEllipseItem *pivotCircle = scene.addEllipse(-2.5,-2.5,5,5);
pivotCircle->setPos(pivotPoint);
QGraphicsRectItem *rect = scene.addRect(-5,-5,10,10);
rect->setPos(itemPosToRotate);
// draw some coordinate frame lines
scene.addLine(-100,0,100,0);
scene.addLine(0,100,0,-100);
// do half-cicle rotation
for(int j=0;j<=5;j++)
for(int i=1;i<=20;i++) {
rect = scene.addRect(-5,-5,10,10);
rect->setPos(itemPosToRotate);
QPointF itemCenter = rect->pos();
QPointF pivot = pivotCircle->pos() - itemCenter;
// your local rotation
rect->setRotation(45);
// your rotation around the pivot
rect->setTransform(QTransform().translate(pivot.x(), pivot.y()).rotate(180.0 * (qreal)i/20.0).translate(-pivot.x(),-pivot.y()),true);
}
view.setScene(&scene);
view.setTransform(view.transform().scale(2,2));
view.show();
EDIT:
In case you meant to rotate around the global coordinate frame origin change the rotations to:
rect->setTransform(QTransform().translate(-itemCenter.x(), -itemCenter.y()).rotate(360.0 * (qreal)j/5.0).translate(itemCenter.x(),itemCenter.y()) );
rect->setTransform(QTransform().translate(pivot.x(), pivot.y()).rotate(180.0 * (qreal)i/20.0).translate(-pivot.x(),-pivot.y()),true);

Resources