Qt给自定义组件的子组件设置回调函数
一、概述
Qt的界面不管是用纯的代码编写,还是用可视化界面编写,其友好度相对来说是比较差的。所以一有空就定义一些小的组件供后续使用时一个好的习惯。
这不,活来了。
需求:借助QSlider、QLineEdit、QPushButton、QLabel定义一些常用的小组件。效果图如下。ps:其中红框,框出来的是一个组件的集合,也就是说下次要是想要选择一张图片并把选择图片的路径写到输入框中的时候。直接调用这个组件就能使用,而不一一个一个组件拼装了。下面的滑动条和加减也是一样的道理。
其实组合组件写起来是非常方便的,唯一需要注意的是把组合组件中的信息回调给外部。基于android的习惯,我没有用信号槽,而是改用了回调函数的形式,我感觉这种方式更加的清晰明了。
使用funcational+lambda。funcational定义和接收函数,lambda实现函数体内容。
下面直接上代码,我把关键部分用红色的字体标注
二、代码示例
ChoiceImageWidget.h
#include <QWidget> #include "../../common/button/Button.h" #include "../../common/edittext/EditText.h" #include "../../common/seekbar/Seekbar.h" #include <QFileDialog> #include <QHBoxLayout> #include <QLabel> #include <QVBoxLayout> #include <iostream> #include <QFileDialog> #include <functional> class ChoiceImageWidget : public QWidget { Q_OBJECT public: ChoiceImageWidget(QWidget *parent = nullptr); ~ChoiceImageWidget(); public: void setCallback(std::function<void(QString)> func); private: std::function<void(QString)> func; };
ChoiceImageWidget.cpp
#include "ChoiceImageWidget.h" ChoiceImageWidget::ChoiceImageWidget(QWidget* parent) : QWidget(parent) { QHBoxLayout* hLayout = new QHBoxLayout(this); EditText* et = new EditText(this); et->setEnabled(false); et->setFixedHeight(30); Button* btnChoiceBtn = new Button(this); btnChoiceBtn->setText("请选择图片"); hLayout->addWidget(et); hLayout->addWidget(btnChoiceBtn); hLayout->setAlignment(Qt::AlignTop); this->setLayout(hLayout); connect(btnChoiceBtn, &Button::clicked, this, [=]() { QString filePath = QFileDialog::getOpenFileName(this, tr("请选择图片"), "C:/Users/DBF-DEV-103/Downloads/", tr("Image Files(*.jpg *.png *.webp *.jpeg)")); et->setText(filePath); func(filePath); }); } void ChoiceImageWidget::setCallback(std::function<void(QString)> func) { this->func = func; } ChoiceImageWidget::~ChoiceImageWidget() { }
使用回调函数
ChoiceImageWidget* choiceImageWidget = new ChoiceImageWidget(this); choiceImageWidget->setFixedWidth(200); choiceImageWidget->setCallback([=](QString filePath) { this->filePath = filePath; qDebug() << "选择图片完成开始打印路径:" << filePath; this->execute(); qDebug() << "开始对此路径执行耗时任务:" << filePath; });
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
· SQL Server 2025 AI相关能力初探
2021-12-08 AndroidVideoCache实现预缓存
2013-12-08 使用Android绘图技术绘制一个椭圆形,然后通过触摸事件让该椭圆形跟着手指移动
2013-12-08 Android解决自定义View获取不到焦点的情况