Qt:捕获和传递信号的最佳机制
我有一个扩展 QWidget 类的类,该类使用 QtDesigner 生成的 Ui 类。如下所示:
class MyWidget : public QWidget
{
signals:
void pushButtonClicked();
// ....
private:
Ui::MyUi ui;
}
MyWidget::MyWidget()
{
ui = new Ui::MyUi();
ui->setupUi(this);
}
现在假设 Ui::MyUi
中有一个 QPushButton * PushButton
字段。该小部件的 UI 没有复杂的业务逻辑。
现在要求每当点击 pushButton
时,这个小部件就应该发出一个信号(我们称之为 pushButtonClicked()
)。现在我能想象实现这一点的唯一方法是:
将
pushButton
对象的clicked()
信号连接到本地插槽,并从那里发出信号pushButtonClicked()
。Install
MyWidget< 。 /code> 作为
pushButton
的 mouseEventFilter 并在MyWidget::mouseClickedEvent
中处理它
还有其他选择吗?比如让 Qt 框架使用 'MyWidget::pushButtonClicked()' 而不是 pushButton- >clicked()
在项目中,我有很多这样的场景,其中需要从像 MyWidget
这样的包装类传递这样的信号,它通过聚合或抽象来包装/抽象 UI继承。一般来说,这被认为是更好设计、代码重用(尤其是代码重用)的最佳方法。当项目处于初期阶段并且不知道这些 UI 中的哪些将来可能需要复杂的业务逻辑时。
请注意,扩展 QPushButton 不是一个选项。
I have a class extending QWidget
class and this class uses a Ui class generated by QtDesigner. Something like following:
class MyWidget : public QWidget
{
signals:
void pushButtonClicked();
// ....
private:
Ui::MyUi ui;
}
MyWidget::MyWidget()
{
ui = new Ui::MyUi();
ui->setupUi(this);
}
Now lets suppose there is a QPushButton * pushButton
field inside Ui::MyUi
. The UI for this widget has no complex business logic.
Now it is required that whenever pushButton
is clicked this widget should emit a signal (lets call it pushButtonClicked()
. Now the only way I can imagine this to be achieved is to:
connect
clicked()
signal ofpushButton
object to a local slot and emit signalpushButtonClicked()
from there.Install
MyWidget
as mouseEventFilter forpushButton
and handle it insideMyWidget::mouseClickedEvent
Are there other options? Like somehow letting Qt framework to use 'MyWidget::pushButtonClicked()' instead of pushButton->clicked()
In the project I have many scenarios like this where such signal passing is needed from the wrapper classes like MyWidget
, which wrap/abstract the UI by aggregation or inheritance. In general which is considered the best approach for better design, code reuse esp. when the project is at nascent stage and it is not known which of these UIs might need complex business logic in the future.
Please note that extending QPushButton is not an option.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以直接连接信号 =)
You can connect signals directly =)