[英]How can I connect a Gtkmm signal to a fuction in another class?
我是 C++ 和 Gtkmm3 的新手。 我需要在另一個類中設置信號,如果不使用小部件類中的函數加載類,我將如何做到這一點。
我不想在 ButtonBox 中重新加載整個 FixedLayout
在 ButtonBox 類中我不想要
FixedLayout instance;
instance.move_widget();
下面顯示了我的代碼
布局.cpp
#include "layout.h"
#include <iostream>
FixedLayout::FixedLayout()
{
fixed.put(box, 0, 0);
add(fixed);
}
void FixedLayout::move_widget(int x, int y)
{
fixed.move(*fixed.get_focus_child(), x, y);
}
ButtonBox::ButtonBox()
{
set_size_request(320, 480);
header.set_size_request(-1, 24);
body.set_size_request(-1, 456);
pack_start(header);
dragger = Gtk::GestureDrag::create(header);
dragger->set_button(GDK_BUTTON_PRIMARY);
dragger->set_propagation_phase(Gtk::PHASE_BUBBLE);
dragger->signal_drag_update().connect(sigc::mem_fun(*this, &ButtonBox::update_drag));
pack_end(body);
}
void ButtonBox::update_drag(bool x, bool y)
{
FixedLayout::move_widget(x, y);
}
布局.h
#ifndef FIXEDLAYOUT_H
#define FIXEDLAYOUT_H
#include <gtkmm.h>
class ButtonBox: public Gtk::VBox
{
public:
ButtonBox();
protected:
Gtk::Button header{"Header"}, body{"Body"};
Glib::RefPtr<Gtk::GestureDrag> dragger;
void update_drag(bool x, bool y);
private:
};
class FixedLayout: public Gtk::ScrolledWindow
{
public:
FixedLayout();
//virtual ~bar();
protected:
void move_widget(int x, int y);
Gtk::Fixed fixed;
ButtonBox box;
private:
};
#endif // FIXEDLAYOUT_H
dragger->signal_drag_update().connect(sigc::mem_fun(*this, &ButtonBox::update_drag));
以下是將信號連接到回調方法的方法。 this
是指向類的實際實例的指針。 那么如何連接到另一個類的實例呢?
使用指針
如果需要將信號連接到另一個類實例的方法,則需要提供指向該實例的指針而不是this
。 一些關於:
signal().connect(sigc::mem_fun(*p, &::callback_name));
這里p
是一個通用指針,讓它成為你的類的一個屬性。 請注意,這會使兩個類相互獨立,因此如果您想讓代碼可重用,通常不是一個好主意。
在您的情況下,您需要在ButtonBox
放置一個指向FixedLayout
實例的指針。
class ButtonBox: public Gtk::VBox
{
private: #could be whatever
FixedLayout *ptofl;
};
在你的構造函數中:
whatever_signal().connect(sigc::mem_fun(*ptofl, &FixedLayout::name_of_the_method));
遺產
另一種方法是使ButtonBox
成為FixedLayout
子FixedLayout
:
class ButtonBox: public Gtk::VBox, public FixedLayout
您需要顛倒兩個類的順序定義。 然后從ButtonBox
您可以訪問FixedLayout
protected 和 public 方法,並且在您的代碼中您只能使用ButtonBox
實例。 將信號連接到回調時,您可以像往常一樣使用this
指針。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.