如何使用方法连接按钮,请单击
How to connect buttons with methods, which will be called on click
我开始编程一些自定义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.
}
相关文章:
- ImGui 在单击按钮后冻结
- 如何在单击按钮FLTK的确切时刻获得小部件的值
- 如何使linedit准备好在单击按钮时键入
- 如何通过单击按钮在QTextEdit中显示文本?
- 通过单击按钮更改标签 GTK C.
- 将文本添加到鼠标位置时,请单击“给出分割故障”
- Qt在单击按钮时调用Child-Window
- 如何使用方法连接按钮,请单击
- 如何使 UI 对象仅在单击按钮后显示在对话框中
- Qt C++单击按钮的事件
- 如何使用C++禁用窗口上的右键单击按钮
- 事件仅在单击按钮时检查
- 右键单击按钮GTKMM-3.0的信号
- 如何通过单击按钮在窗口上生成对象
- 单击按钮后,如何在QT中更改窗口中的信息
- 单击按钮时控制qt中的循环
- 尝试在单击按钮时捕获编辑框中的文本,然后显示到另一个编辑框
- 单击按钮时,全局变量包含垃圾
- 单击按钮后对QML矩形的颜色设置动画
- 正在检测何时单击按钮?[C++,WinAPI]