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; });
浙公网安备 33010602011771号