问题描述
我一直在 YouTube 上观看 Qt 教程系列,其中作者展示了如何在按下按钮时调用函数.他在 Qt Creator IDE 中右键单击按钮并选择转到插槽",他从中选择了触发生成函数的信号.由于我习惯于使用 Netbeans 进行开发,因此我只是尝试使用嵌入式 Qt Designer 来遵循他的示例.不幸的是,当我右键单击我的按钮或任何小部件时,没有转到插槽..."条目.当然,我可以为我的主窗口创建一个新插槽,然后将按钮的信号连接到它,但是使用单个功能来完成它对我来说似乎更方便和干净.有没有办法解决,或者如果没有,至少是一种完全通过代码处理的方法,而不必为服务于不同目的的每个按钮在主窗口中添加一个新插槽?感谢您的帮助.
I've been watching a Qt tutorial series on YouTube, in which the author shows how to call a function, when a button is pressed. He right-clicked on the button in Qt Creator IDE and chose "Go to slot", from where he chose the signal which would fire the generated function. Since I am used to develop with Netbeans, I simply tried to follow his example using the embedded Qt Designer. Unfortunately, there is no "Go to slot..." entry when I right-click on my button or any widget. I could, of course, create a new slot for my main window and then connect the button's signal to it, but doing it with a single function just seems way more convenient and clean to me. Is there a way to fix is, or if not, at least a way to do with via code entirely, without having to add a new slot to the main window for every single button that servers a different purpose? Thanks for your help.
推荐答案
虽然我不知道为什么 Netbeans 中的 QtDesigner 不提供此功能,但我知道该功能的作用:它只是创建了一个带有特殊插槽的插槽您的小部件类中的名称.请注意,它不添加连接语句.它使用自动连接功能,其工作原理如下:
While I don't know why the QtDesigner in Netbeans doesn't provide this feature, I know what the feature does: It just creates a slot with a special name in your widget class. Note that it does not add a connect statement. It uses the automatic connection feature, which works like this:
对于名称与此模式匹配的每个插槽:
For each slot which name matches this pattern:
void on_X_Y(...)
它将连接到名为X
的对象的名为Y
的信号.因此,如果您有一个名为 button
的 QPushButton,并且您想处理 pressed
信号,只需创建一个具有以下签名的插槽:
it will be connected to the signal named Y
of the object named X
. So if you have a QPushButton named button
, and you want to handle the signal pressed
, simply create a slot with the following signature:
void on_button_pressed()
如果你想知道这个槽是如何连接到信号的:这发生在 setupUi()
末尾的 ui_...h
文件中:
If you wonder how this slot gets connected to the signal: This happens in the ui_...h
file at the end of setupUi()
:
QMetaObject::connectSlotsByName(WidgetName);
这篇关于Qt Designer,缺少“转到插槽"在上下文菜单中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!