随笔 - 632  文章 - 17  评论 - 54  阅读 - 93万

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;
    });

 

posted on   飘杨......  阅读(221)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
历史上的今天:
2021-12-08 AndroidVideoCache实现预缓存
2013-12-08 使用Android绘图技术绘制一个椭圆形,然后通过触摸事件让该椭圆形跟着手指移动
2013-12-08 Android解决自定义View获取不到焦点的情况
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示