qt for ios扫描二维码功能实现-程序员宅基地

问题:  

公司项目考虑到跨平台一直都是用qt做,由于项目需求,项目上要增加一个二维码扫描功能,在安卓可以用QVideoProbe实现抓取摄像头视频帧,用QZxing解码图片,从而实现二维码扫描,但是在ios上,QVideProbe并不支持,所以只好选择其他抓取视频帧的方法,考虑使用OPencv实现抓取视频帧,但是在查看ios文档时,ios7 以上直接支持二维码扫描功能,所以放弃使用opencv抓取 + zxing解码的方法.从而采取ios官方提供的二维码解码功能.

 

实现:

由于我们项目ui一直是用qml实现,但是要实现扫描二维码功能,需要调用AVFoundation中的方法,同时要显示ios中的ui显示摄像头及返回qml 键.所以这里需要结合oc 和 qt编程.

直接上代码:

pro文件增加

ios {

  OBJECTIVE_SOURCES += IOSView.mm  \  # object c++ file

       IOSCamera.mm 

  HEADER +=  IOSView.h \

      IOSCamera.h \

      IOSCameraViewProtocol.h 

 

  QMAKE_LFLAGS += -framework AVFoundation  #add AVfoundation framework

 

  QT += gui private

}

重新qmake生成xcode project

IOSView.#include <QQuickItem>

class IOSView : public QQuickItem
{
    Q_OBJECT
    Q_PROPERTY(QString qrcodeText READ qrcodeText WRITE setQrcodeText NOTIFY qrcodeTextChanged)
        
public:
    explicit IOSView(QQuickItem *parent = 0);
        
    QString qrcodeText() {
       return m_qrcodeText;
    }
    
    void setQrcodeText(QString text){
        m_qrcodeText = text;
        emit qrcodeTextChanged();
    }
        
   QString m_qrcodeText;
        
        
public slots:
    void startScan();  //for open ios camera scan and ui
        
private:
    void *m_delegate;  //for communication with qt
        
signals:
    void qrcodeTextChanged();  
    void stopCameraScan();  //show qml
};

IOSView..mm

#include <UIKit/UIKit.h>
#include <QtQuick>
#include <QtGui>
#include <QtGui/qpa/qplatformnativeinterface.h>
#include "IOSView.h"
#include "IOSCamera.h"

@interface IOSCameraDelegate : NSObject <IOSCameraProtocol> {
    IOSView *m_iosView;
}
@end

@implementation IOSCameraDelegate

- (id) initWithIOSCamera:(IOSView *)iosView
{
    self = [super init];
    if (self) {
        m_iosView = iosView;
    }
    return self;
}

-(void) scanCancel{
    emit m_iosView->stopCameraScan();
}

-(void) scanResult :(NSString *) result{
    m_iosView->setQrcodeText(QString::fromNSString(result));
}

@end

IOSView::IOSView(QQuickItem *parent) :
    QQuickItem(parent), m_delegate([[IOSCameraDelegate alloc] initWithIOSCamera:this])
{
}
    
void IOSView::startScan()
{
    // Get the UIView that backs our QQuickWindow:
    UIView *view = static_cast<UIView *>(QGuiApplication::platformNativeInterface()->nativeResourceForWindow("uiview", window()));
    UIViewController *qtController = [[view window] rootViewController];

    IOSCamera *iosCamera = [[[IOSCameraView alloc] init ]autorelease];
    iosCamera.delegate = (id)m_delegate;
    // Tell the imagecontroller to animate on top:
    [qtController presentViewController:iosCamera animated:YES completion:nil];
    [iosCamera startScan];
}

  

IOSCameraViewProtocol.h

#import <Foundation/Foundation.h>

@protocol CameraScanViewProtocol <NSObject>

@required
-(void) scanCancel;
-(void) scanResult :(NSString *) result;


@end

  

IOSCamera.h

#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>
#import "CameraViewProtocol.h"

@interface IOSCamera : UIViewController <AVCaptureMetadataOutputObjectsDelegate>{
    id<CameraScanViewProtocol> delegate;
}
@property (retain, nonatomic) IBOutlet UIView *viewPreview;
- (IBAction)backQtApp:(id)sender;

-(void) startScan;

@property (retain) id<CameraScanViewProtocol> delegate;

@end

  

IOSCamera.cpp#import "IOSCamera.h"


@interface IOSCamera ()
@property (nonatomic,strong) AVCaptureSession * captureSession;
@property (nonatomic,strong) AVCaptureVideoPreviewLayer * videoPreviewLayer;-(BOOL) startReading;
-(void) stopReading;
-(void) openQtLayer;
@end

@implementation CameraScanView
@synthesize delegate;    //Sync delegate for interactive with qt

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    // Initially make the captureSession object nil.
    _captureSession = nil;
    
    // Set the initial value of the flag to NO.
    _isReading = NO;
    
    // Begin loading the sound effect so to have it ready for playback when it's needed.
    [self loadBeepSound];
} - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } /* #pragma mark - Navigation - (void)dealloc { [_viewPreview release]; [super dealloc]; } - (void)viewDidUnload { [self setViewPreview:nil]; [super viewDidUnload]; }
- (IBAction)backQtApp:(id)sender {     [delegate scanCancel];
    [self stopReading];
}

-(void) openQtLayer{
    // Bring back Qt's view controller:
    UIViewController *rvc = [[[UIApplication sharedApplication] keyWindow] rootViewController];
    [rvc dismissViewControllerAnimated:YES completion:nil];
}

-(void) startScan{
    if (!_isReading) {
        // This is the case where the app should read a QR code when the start button is tapped.
        if ([self startReading]) {
            // If the startReading methods returns YES and the capture session is successfully
            // running, then change the start button title and the status message.
            NSLog(@"Start Reading !!");
        }
    }
}

#pragma mark - Private method implementation

- (BOOL)startReading {
    NSError *error;
    
    // Get an instance of the AVCaptureDevice class to initialize a device object and provide the video
    // as the media type parameter.
    AVCaptureDevice *captureDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    
    // Get an instance of the AVCaptureDeviceInput class using the previous device object.
    AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:captureDevice error:&error];
    
    if (!input) {
        // If any error occurs, simply log the description of it and don't continue any more.
        NSLog(@"%@", [error localizedDescription]);
        return NO;
    }
    
    // Initialize the captureSession object.
    _captureSession = [[AVCaptureSession alloc] init];
    // Set the input device on the capture session.
    [_captureSession addInput:input];
    
    
    // Initialize a AVCaptureMetadataOutput object and set it as the output device to the capture session.
    AVCaptureMetadataOutput *captureMetadataOutput = [[AVCaptureMetadataOutput alloc] init];
    [_captureSession addOutput:captureMetadataOutput];
    
    // Create a new serial dispatch queue.
    dispatch_queue_t dispatchQueue;
    dispatchQueue = dispatch_queue_create("myQueue", NULL);
    [captureMetadataOutput setMetadataObjectsDelegate:self queue:dispatchQueue];
    [captureMetadataOutput setMetadataObjectTypes:[NSArray arrayWithObject:AVMetadataObjectTypeQRCode]];
    
    // Initialize the video preview layer and add it as a sublayer to the viewPreview view's layer.
    _videoPreviewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:_captureSession];
    [_videoPreviewLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill];
    [_videoPreviewLayer setFrame:_viewPreview.layer.bounds];
    [_viewPreview.layer addSublayer:_videoPreviewLayer];
    
    
    // Start video capture.
    [_captureSession startRunning];
    _isReading = YES;
    return YES;
}


-(void)stopReading{
    // Stop video capture and make the capture session object nil.
    [_captureSession stopRunning];
    _captureSession = nil;
   
   // Remove the video preview layer from the viewPreview view's layer.
   [_videoPreviewLayer removeFromSuperlayer];
   _isReading = NO;
   [self openQtLayer];
}

#pragma mark - AVCaptureMetadataOutputObjectsDelegate method implementation

-(void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection{
    
    // Check if the metadataObjects array is not nil and it contains at least one object.
    if (metadataObjects != nil && [metadataObjects count] > 0) {
        // Get the metadata object.
        AVMetadataMachineReadableCodeObject *metadataObj = [metadataObjects objectAtIndex:0];
        if ([[metadataObj type] isEqualToString:AVMetadataObjectTypeQRCode]) {
            // If the found metadata is equal to the QR code metadata then update the status label's text,
            // stop reading and change the bar button item's title and the flag's value.
            // Everything is done on the main thread.
            [delegate scanResult:[metadataObj stringValue]];  //send scan result to qt show
            
            [self performSelectorOnMainThread:@selector(stopReading) withObject:nil waitUntilDone:NO];
            
            _isReading = NO;
        }
    }
}

@end
 

OK.大概流程就这些了,添加xib文件等就不介绍了.

 

转载于:https://www.cnblogs.com/fuyanwen/p/4428599.html

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/weixin_30496751/article/details/95111280

智能推荐

推荐系统基本认识_稀疏矩阵 树模型 神经网络-程序员宅基地

文章浏览阅读992次。太长不读版:由推荐系统带来的推荐服务基本上已经渗透到我们生活的方方面面,本文作为浅谈推荐系统的基础篇,主要从下面几个维度介绍推荐系统的相关知识:什么是推荐系统推荐系统在商业中的地位推荐系统、搜索引擎及广告的关系推荐系统的关键元素推荐系统相关的算法篇幅较长,可能大部分道友比较关心算法部分,所以重点罗列了推荐系统算法思维演进史,每类算法理论点到即止,没有提供详细细节,但给出了相关阅读资..._稀疏矩阵 树模型 神经网络

BytePS源码解析(1)-理论-程序员宅基地

文章浏览阅读2.2k次,点赞3次,收藏8次。最近因为工作需要,研究了一下字节跳动开源的BytePS,虽然其名字上带有"PS"两字,但是研究后发现它其实并不是一个传统的PS架构,而是all-reduce和PS的一个融合,这个在后面会详细说。网络上有一些关于BytePS创新性的一些质疑,这个见仁见智,我个人感觉撇开创新性,BytePS的理论还是比较优雅的,另外根据初步的测试,效果也确实很不错,思路和代码都很有参考价值。因此尝试写个系列文章来记录一下,本篇是第一篇,先从BytePS的论文入手,了解它的一些理论要点。(作者水平有限,如有谬误敬..._byteps

三星最新推出的2416芯片相比2440具有压倒性的优势_三星2416缓存-程序员宅基地

文章浏览阅读983次。1. 性能:2416 主频400MHz和2440持平,但是2416是ARM926JES内核,是ARM920T的增强版本,运行速度方面比2440要快得多。2. 显示方面:2416支持2D图形加速,最高分辨率可以支持1024x768,24位真彩。同_三星2416缓存

安卓和苹果:自定义参数安装_appstore 安装应用后,传递安装参数-程序员宅基地

文章浏览阅读549次。文章目录产品需求需求分析实现方案1、安卓方案(1)渠道包(2)设备号匹配2、iOS方案(1)App Store Connect 来源分析(2)通过 SFSafariViewController 传递 cookie(3)IDFA3、设备通用方案(1)IP+UA(2)剪贴板方法限制:小结4、第三方工具优点:参考产品需求由于双十一期间要开展多渠道推广,市场运营部要求,对每个渠道下用户的安装来源做详细判断,获取每个用户的安装来源渠道,如官网、推广页面、地推人员、广告跳转、应用商店下载等多个渠道,并且追踪每个渠道_appstore 安装应用后,传递安装参数

视频跟踪——CMT算法-程序员宅基地

文章浏览阅读2.1k次,点赞4次,收藏6次。*部分内容转载于http://blog.csdn.net/songrotek/article/details/47662617CMT,全称是Clustering of Static-Adaptive Correspondences for Deformable Object Tracking主要应用功能为对于物体的视觉跟踪。视频跟踪常见的方法思路可以分为三大类:第一_cmt算法

Asp.Net Mvc框架下的FckEdit控件 从客户端检测到有潜在危险的Request.Form值_"从客户端(fckeditorval=\"<p>空</p>\")中检测到有潜在危险的 request-程序员宅基地

文章浏览阅读1.9k次。从客户端(FckTextBox=" 说明: 请求验证过程检测到有潜在危险的客户端输入值,对请求的处理已经中止。该值可能指示危及应用程序安全的尝试,如跨站点的脚本攻击。通过在 Page 指令或 配置节中设置 validateRequest=false 可以禁用请求验证。但是,在这种情况下,强烈建议应用程序显式检查所有输入。 异常详细信息: System.Web.HttpRequest_"从客户端(fckeditorval=\"空\")中检测到有潜在危险的 request.form 值。"

随便推点

prometheus监控多个MySQL实例_prometheus 多mysql-程序员宅基地

文章浏览阅读6.1k次。之前文章介绍了prometheus、grafana、exporter的安装以及基本使用,在添加mysql监控节点的部分,使用了分离部署+环境变量的方式,如下所示:添加MySQL监控添加MySQL监控主机,这里以添加10.10.20.14为例进行说明。解压exporter压缩包。[root@localhost~]#tarxfmysqld_exporter-0.10.0...._prometheus 多mysql

大脑模型认知实验报告(脑与认知期末考核)_端脑实验报告-程序员宅基地

文章浏览阅读1k次,点赞31次,收藏24次。大脑模型认知实验报告_端脑实验报告

Error creating bean with name ‘BAdminMapper‘ defined in file [C:\Users\ASUS\Desktop\FleakMarket-mast-程序员宅基地

文章浏览阅读3.4k次,点赞3次,收藏3次。项目最初是可正常运行的,我只是把一些.java文件放到(就是直接用鼠标拖动文件)其他包下,然后出现下面这个对话框Refactor后,当我重新Run‘Application’时,意外发生了!Stopping service [Tomcat]控制台报错提示如下:2021-12-24 01:14:34.511 WARN 6440 --- [ restartedMain] ConfigServletWebServerApplicationContext : Exception encountered

Java Swing中的多线程_swing 多线程-程序员宅基地

文章浏览阅读4.3k次,点赞12次,收藏40次。对Java Swing中的多线程操作进行介绍,以创建一个如下图所示的计时器界面为例对Swing中的多线程进行介绍在该计时器界面中按下start键开始计时,按下stop键,计时停止..._swing 多线程

Element form表单 表单域对齐_el-form-item右对齐-程序员宅基地

文章浏览阅读2.6w次。在form表单组件中,我们可以通过 label-position 属性来改变表单域或标签的位置,可选的值有 top/left/right ,默认的是 right ,lable-position 必须要和 label-width(表单域标签的宽度,作为 Form 直接子元素的 form-item 会继承该值) 共同使用,才会生效。..._el-form-item右对齐

实用的网站-程序员宅基地

文章浏览阅读750次。学习知乎:www.zhihu.com 简答题:http://www.jiandati.com/ 网易公开课:https://open.163.com/ted/ 网易云课堂:https://study.163.com/ 中国大学MOOC:www.icourse163.org 网易云课堂:study.163.com 哔哩哔哩弹幕网:www.bilibili.com 我要自学网:www...