Search code examples
qt3d2dcoordinatesqt3d

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.


Solution

  • 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:

    1. 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)
    2. Attach the object picker as a component to the object you want to pick
    3. 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).