PyQt、Qt、一个事件处理程序可处理多个项目
我的表单上有几个复选框,我不想为每个复选框编写单独的事件处理程序,因为它们都将实现相同的逻辑。相反,我只想编写一个事件处理程序来了解单击了哪个复选框。
例如,在 Delphi 中,我可以这样使用它:
function click_handler(sender):
begin
checked_box := sender.tag;
end;
这里我记得某个变量中当前复选框的编号(标签属性是在 Delphi IDE 中手动设置的)。
我进行了搜索,但找不到如何使用 Qt 实现此功能,因为事件处理程序没有 sender
参数。
我是这样实现的,但是不太方便:
# assign handlers (n assignments)
checkbox_1.clicked.connect(self.cb_1_click)
...
checkbox_<n>.clicked.connect(self.cb_<n>_click)
# separate handler for each check box (n functions, doing the same stupid work)
def cb_1_click:
self.cb_click(sender=1)
...
def cb_<n>_click:
self.cb_click(sender=n)
# main check box click logic (1 function)
def cb_click(sender):
# do something common for all checkboxes
谢谢。
I have a couple of checkboxes on my form, and I don't want to write separate event handler for each, because they all will implement the same logic. Instead I want to write just one event handler that will know about what checkbox has been clicked.
E.g. in Delphi I can use it this way:
function click_handler(sender):
begin
checked_box := sender.tag;
end;
Here I remember current checked box number in some variable (tag property was manually set in Delphi IDE).
I searched and can't find how I can implement this using Qt, because event handlers don't have sender
argument.
I implemented it like this, but it's not convenient:
# assign handlers (n assignments)
checkbox_1.clicked.connect(self.cb_1_click)
...
checkbox_<n>.clicked.connect(self.cb_<n>_click)
# separate handler for each check box (n functions, doing the same stupid work)
def cb_1_click:
self.cb_click(sender=1)
...
def cb_<n>_click:
self.cb_click(sender=n)
# main check box click logic (1 function)
def cb_click(sender):
# do something common for all checkboxes
Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以在插槽中使用 QObject::sender() 来查找谁发出了信号。
另外,您可能想查看 QSignalMapper ,它正是为了解决这些问题而设计的。
You may use QObject::sender() in slots to find out who emitted the signal.
Also you might want to check out QSignalMapper which is intended exactly for solving these problems.