如何连接按钮与方法,将点击调用

问题描述:

我开始编程一些自定义gui应用程序。但我需要知道如何用某种方法连接按钮。
例如我有:
如何连接按钮与方法,将点击调用

class Button 
{ 
private: 
    string Text; 
    /*etc*/ 
public: 
    string GetLabel(); 
    void SetLabel(string label); 
    void Connect(/*method name as param*/) 
    { 
     //TODO -this is that thing i need help here 
     /*this is method for connecting button with method, which will be 
      called on click, which im asking for help*/ 
    } 
}; 

class Window 
{ 
private: 
    int sizeX,sizeY; 
public: 
    void Put(Button * button,int _hpos,int _vpos); 
    void Show(); 
    /*etc */ 
}; 

class MyWindow : public Window 
{ 
public: 
    MyWindow() 
    { 
     InitializeComponents(); 
    } 
    void Run() 
    { 
     this -> Put(btn1,10,10); //put button in window at position 10,10 
     this -> Show(); 
    } 
private: 
    Button * btn1; 
    void InitializeComponents() 
    { 
     btn1 = new Button(); 
     btn1 -> Connect(on_btn1_click); //select which method will be called when user click this button, which I dont know how to do so pls help 
    } 
    void on_btn1_click() //this method is called when user click the button 
    { 
     //do something if user clicked btn1 
    } 

}; 

int main() 
{ 
    MyWindow * win1 = new MyWindow(); 
    win1 -> Run(); 
    return 0; 
} 

所以有mywindow的类内部私有方法时用户点击按钮将被称为(BTN1)。方法Connect()选择用户单击按钮时将使用哪种方法进行调用。

+1

您正在使用哪种GUI框架?你使用哪种平台或操作系统? –

+0

这是基于curses。我想让诅咒更加可用,所以我试图创建一些oop框架。 – T0maas

您可以检查鼠标是否位于按钮/ UI对象上,如果不是触发命令/事件。

const Button& GetObjectBelowMouse(int xMousePos, int yMousePos) // This would be equavalent to your Connect type 
{ 
    // all buttons would be your container of buttons/GUI objects. 
    for(const auto& button : allButtons) 
    { 
     // top,bottom,left,right would be the bounding rectangle that encapsulates the coordinates of the object 
     if((xMousePos > button.left && xMousePos < button.right) && (yMousePos > button.bottom && yMousePos < buttom.top)) 
     { 
      return button; 
     } 
    } 
    // in this case we have a different constructor that creates a "empty" button that has no function 
    return Button(NO_OBJECT); 
} 

// the usage would be something like 

int main() 
{ 
    /* 
     .. create button, set it's possition, etc 
    */ 

    // Option 1 
    if(GetObjectBelowMouse(mouse.x, mouse.y).type != NO_OBJECT) 
    { 
     // Do whatever you want, you know that the user has clicked a valid object 
     button.Foo(); 
    } 

    // Option 2 
    GetObjectBelowMouse(mouse.x, mouse.y).Foo(); // You know that every button has a foo object, and that NO_OBJECT has a foo that does nothing, so you don't need to compare if it is NO_OBJECT or not. 
} 
+0

我在Qt框架中找到了一些东西。有一些方法称为QObject :: connect。它对我来说非常合适,但有一个问题。 Qt使用* .so的大量ammout,所以我决定不使用Qt。所以我需要帮助如何创建替代QObject :: connect()。 – T0maas