Wednesday, February 17, 2010

How to update a GTK::TextView from a separate object

If you are wondering how to update a text box that was created in your GTK GUI from a separate object then you have come to the right place.  As of this positing date I have searched for the solution to this problem, but there is no real mention on how to do it.  The basic premise is to get the underlying object of the TextView and pass it to the object that wants to edit it.  Then that object must create a pointer to this object and can then access its information.  Anyways lets get to it.

File List:
  • textEdit.cpp - This is where the code is written to update the TextView declared in example.cpp
  • textEdit.h - This is the header file for the code that will update the TextView declared in example.cpp
  • example.cpp - This is where the GUI and TextView are defined

textEdit.h

#include 
using namespace std;

class textEdit{

private:
   GtkTextView *l_text_view;
   Glib::RefPtr l_text_view_buffer;

public:
   textEdit(){l_text_view = NULL; l_text_view_buffer = Gtk::TextBuffer::create();}
   void updateText();
   void setTextViewObject(GtkTextView *text_view){l_text_view = text_view;}
   virtual ~textEdit(){}

}


textEdit.cpp

#include "textEdit.h"

void updateText(){
   string update_words = "Testing, Testing, Testing";

   // Setup a temporary pointer to a TextView
   Gtk::TextView *temp;

   // Get the old buffer and append the new update to it (this can be changed to whatever)
   string bufferNew = update_words + "\n" + l_text_view_buffer->get_text();

  // Set the new buffer text to the actual buffer
  l_text_view_buffer->set_text(bufferNew);

  // Take the l_text_view and assign this pointer to temp
  temp = Glib::wrap(l_text_view,false);

  // Update the temp TextView with the buffer
  temp->set_buffer(l_text_view_buffer);
}


example.cpp

.
.
.

// Create the object
textEdit textEdit;

// Send the text_view object.  This would be defined in you header file as such:
//      Gtk::TextView text_view;
textEdit.setTextViewObject(text_view.gobj)

.
.
.

No comments:

Post a Comment