如何使用方法连接按钮,请单击

How to connect buttons with methods, which will be called on click

本文关键字:请单击 按钮 连接 使用方法      更新时间:2023-10-16

我开始编程一些自定义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;
}

因此,当用户单击按钮(BTN1)时,MyWindow类内有私有方法。方法Connect()选择当用户单击按钮时,将使用哪种方法用于调用。

您可以检查鼠标是否在按钮/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.
}