Programmatically adding OpenGL view to window

Discussion in 'Mac Programming' started by Starfox, Nov 29, 2011.

  1. macrumors regular

    Apr 7, 2011
    What's the proper way to programmatically instantiate and add an OpenGL view to a window? I'm doing a simple GUI application but I'd like to create it programmatically so I can ask for Core 3.2 profile and fallback to 2.x if that's not available.
  2. macrumors newbie

    Aug 20, 2006
    Same issue here

    Looks like we're trying to figure out the same thing.

    I've got a simple project where I just want a window with an NSOpenGLView covering the entire window contentView colored blue and a triangle displayed. The window displays, but I see no NSOpenGLView content.

    I've got my project here:

    Hopefully, I'm not threadjacking. I think we, basically, have the same question.



    BTW, I used the code found in to help me get started on my as-of-yet-flawed project.
  3. Moderator emeritus


    Jun 15, 2000
    That is not a simple project if you're starting out with Cocoa/OpenGL integration.

    Try my sample project here which just displays a black background and a red triangle:

    Then build upon that slowly.


    Assuming you're setting up the 3.2 vs 2.x check via NSOpenGLPixelFormat, its initWithAttributes: will return nil if it can't initialize with the attributes given, so you could create a method to check for that and revert to 2.x settings if the 3.2 attributes fail.

    An OpenGL view is an NSView, so it's added to a window just like any other view: create the window, create the OpenGL view, and set it as the window's content view, then show the window.
  4. macrumors newbie

    Aug 20, 2006

    I'm finding that this is the case, actually. :)

    Thanks for the link to your code! It will definitely help me.
  5. thread starter macrumors regular

    Apr 7, 2011
    My problem isn't initializing OpenGL etc. - my problem is that I want to programmatically (in applicationDidFinishLaunching:) add an NSOpenGLView* to my window. I know how to alloc and init it with pixel format attributes, but now that I have this NSOpenGLView* and NSWindow*, how can I "insert" the view inside the window?
  6. macrumors 65816


    Dec 16, 2010

    If the NSOpenGLView is to be the sole content in the window then:
    window.content = openGLView; // or [window setContent:openGLView];
    If there is to be other content in the window, then you'd added it as subview of a view already in the window.
    [viewAlreadyInWindow addSubview:openGLView];
  7. thread starter macrumors regular

    Apr 7, 2011
    Thanks, that worked perfectly!

Share This Page