3
$\begingroup$

This function is supposedly the one for fitting the camera to 3D view with python(with mouse cursor hovering over the 3d view):

import bpy
for area in bpy.context.screen.areas:
    if area.type == 'VIEW_3D':
        if bpy.ops.view3d.view_center_camera.poll()
            bpy.ops.view3d.view_center_camera()

Hitting home keyboard-button activates view_center_camera function and does what it is supposed to, so the function seems correct and working.

It just doesn't work when I call the function from Python(like mentioned above). What is the correct way?

$\endgroup$
4
  • $\begingroup$ How do you call the function from Python? What is your actual code? Please edit your first post and add this piece. $\endgroup$
    – Tiles
    Commented Dec 4, 2017 at 7:15
  • $\begingroup$ And error message.. Educated guess: You need to be in 3d view context $\endgroup$
    – batFINGER
    Commented Dec 4, 2017 at 11:47
  • $\begingroup$ You're not calling the function at all. A call needs parentheses, so bpy.ops.view3d.view_center_camera(). $\endgroup$
    – dr. Sybren
    Commented Dec 4, 2017 at 16:24
  • $\begingroup$ Thank you very much for the help. I can't seem to get my head around a solution doing it this way, however I found a solution for what I want to do here: blender.stackexchange.com/questions/16493/… $\endgroup$
    – tintwotin
    Commented Dec 4, 2017 at 23:00

1 Answer 1

3
$\begingroup$

This code works in 2.80:

import bpy

def find_3d_area():
    for area in bpy.context.window.screen.areas:
        if area.type == 'VIEW_3D':
            return area

area = find_3d_area()
if area:
    override = {
        'area': area,
        'region': area.regions[0],
    }
    if bpy.ops.view3d.view_center_camera.poll(override):
        bpy.ops.view3d.view_center_camera(override)

Blender operators have optional parameter "context". In almost all cases, you don't need to override it, but this case is somewhat special.

In this case, you have to override area and region. I'm not able to explain into the deep why exactly these two keys are needed. It's only the result of my debugging inside C code of Blender, and trial/error in Python.

$\endgroup$
4
  • $\begingroup$ Hello and welcome. Thanks for the answer. Could you add a small description to your answer explaining what the code does or how it works? $\endgroup$ Commented Apr 30, 2019 at 12:15
  • $\begingroup$ typo line 14 btw. needs at the end : $\endgroup$
    – spiraloid
    Commented Aug 21, 2020 at 11:52
  • $\begingroup$ thanks @spiraloid , fixed $\endgroup$
    – rooobertek
    Commented Aug 24, 2020 at 10:33
  • $\begingroup$ this does not work for blender 3.2 and above where override object is deprecated. can you present a solution that works with version 3.5 using with statement and temp_override? $\endgroup$
    – Harry McKenzie
    Commented Apr 20, 2023 at 15:49

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .