如何覆盖 TextBuffer 的默认信号处理程序

How to override default signal handler of TextBuffer

我正在尝试覆盖 Gtk::TextView 的默认 on_erase 信号处理程序。我派生 TextBuffer 并覆盖默认处理程序;但覆盖不起作用。使用cast_static时,RefPtr有效,但使用cast_dynamic时,RefPtr为空。

#include <gtkmm.h>
#include "CTextBuffer.h"
class CMain : public Gtk::Window
{
public:
   CMain();
   virtual ~CMain();
private:
   Gtk::TextView m_textView;
   Glib::RefPtr<CTextBuffer> m_refTextBuffer;
};

#include "CMain.h"
CMain::CMain()
{
   Glib::RefPtr<Gtk::TextBuffer> refTextBuffer = Gtk::TextBuffer::create();
   m_refTextBuffer =  Glib::RefPtr<CTextBuffer>::cast_dynamic(refTextBuffer);
   m_textView.set_buffer(m_refTextBuffer);
   add(m_textView);
   show_all();
}
CMain::~CMain()
{}

#include <gtkmm.h>
class CTextBuffer : public Gtk::TextBuffer
{
public:
   CTextBuffer();
   virtual ~CTextBuffer();
protected:
   virtual void on_erase(const TextBuffer::iterator& range_start, const TextBuffer::iterator& range_end);
};

#include "CTextBuffer.h"
CTextBuffer::CTextBuffer() {}

CTextBuffer::~CTextBuffer() {}

void CTextBuffer::on_erase (const TextBuffer::iterator& range_start, const TextBuffer::iterator& range_end)
{
   Gtk::TextBuffer::on_erase(range_start, range_end);
}

只需使用您自己的类型的引用:

CMain::CMain()
{
    Glib::RefPtr<CTextBuffer> refTextBuffer{ new CTextBuffer };
    m_textView.set_buffer(refTextBuffer);
    add(m_textView);
    show_all();
}

void CTextBuffer::on_erase (const TextBuffer::iterator& range_start, const TextBuffer::iterator& range_end)
{
    std::cout << "Own override was called" << std::endl;
    Gtk::TextBuffer::on_erase(range_start, range_end);
}

您可以在此处找到有关如何使用自己的派生小部件的更多信息:

https://developer.gnome.org/gtkmm-tutorial/stable/sec-builder-using-derived-widgets.html.en