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

智能推荐

压缩字符串 实现思路及练习题-程序员宅基地

文章浏览阅读413次,点赞15次,收藏4次。实现思路:遍历当前字符串,从第一个元素开始,遍历至倒数第二个元素,分别获取当前字符以及下一个字符然后对当前字符与下一个字符进行判断,如果相邻字符相等,表示连续相同,对其进行累加计数。否则相邻字符不相等,表示连续中断,将之前计数完成的字符+字符个数加到字符串末尾,并重新设置要比较的字符,且重新计数。题目:压缩字符串"AAAABBBCCDDDDEEEEEEFFF"使得其输出结果为A4B3C2D4E6F3。输入:AAAABBBCCDDDDEEEEEEFFF。输出:A4B3C2D4E6F3。

python字符串切片用法_Python字符串切片操作知识详解-程序员宅基地

文章浏览阅读541次。一:取字符串中第几个字符print "Hello"[0] 表示输出字符串中第一个字符print "Hello"[-1] 表示输出字符串中最后一个字符二:字符串分割print "Hello"[1:3]#第一个参数表示原来字符串中的下表#第二个阐述表示分割后剩下的字符串的第一个字符 在 原来字符串中的下标这句话说得有点啰嗦,直接看输出结果:el三:几种特殊情况(1)print "Hello"[:3] ...

120、仿真-51单片机温湿度光照强度C02 LCD1602 报警设计(Proteus仿真+程序+元器件清单等)-程序员宅基地

文章浏览阅读464次。(1)有优异的性能价格比。(2)集成度高、体积小、有很高的可靠性。单片机把各功能部件集成在一块芯片上,内部采用总线结构,减少了各芯片之间的连线,大大提高了单片机的可靠性和抗干扰能力。另外,其体积小,对于强磁场环境易于采取屏蔽措施,适合在恶劣环境下工作。(3)控制功能强。为了满足工业控制的要求,一般单片机的指令系统中均有极丰富的转移指令、I/O口的逻辑操作以及位处理功能。单片机的逻辑控制功能及运行速度均高于同一档次的微机。(4)低功耗、低电压,便于生产便携式产品。

国内几款常用热门音频功放芯片-低功耗、高保真_常用hifi芯片-程序员宅基地

文章浏览阅读2.8k次。工作电源电压范围:5V~28V;2、NTP8918;支持2 CH Stereo (15W x 2 BTL)该芯片RS DRC动态功率控制,有效防止破音,其内部设计有非常完善的过耗保护电路,它的音色非常甜美,音质醇厚,颇有电子管的韵味,适合播放比较柔和的音乐,2*16段可调PEQ,加入APEQ功能,真切改善音质,常应用于AI智能音箱上。目前,在手机终端上,音乐手机一般采用CODEC +PA的方式,CODEC要求极高的信噪比、丰富的编解码功能和接口,此外,为了支持16Ω的耳机,也需要较好品质的耳机功率放大器。_常用hifi芯片

.Net内存泄露原因及解决办法_.net内存泄露的解决方法-程序员宅基地

文章浏览阅读296次。&amp;nbsp;1.&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;什么是.Net内存泄露(1).NET 应用程序中的内存您大概已经知道,.NET 应用程序中要使用多种类型的内存,包括:堆栈、非托管堆和托管堆。这里我们需要简单回顾一下。以运行..._.net内存泄露的解决方法

PHP从入门到精通pdf-程序员宅基地

文章浏览阅读2.2k次。链接:https://pan.baidu.com/s/1aveXrqeTnILsc9jgiuCNsQ 密码:570u 本书为完整版,以下为内容截图:

随便推点

70个常用电脑快捷键,帮你工作效率提升100倍!职场新人必备!_快捷键可以帮助自己-程序员宅基地

文章浏览阅读2k次,点赞11次,收藏44次。电脑快捷键不仅可以帮助我们熟练的操作电脑,还可以帮助我们快速提升自己的工作效率,从此跟加班说拜拜!但由于电脑快捷键过于繁多不方便我们记忆!那么今天小编为大家整理的70个Wordows、Ctrl、Alt、Shift组合快捷键,运用好的话能够帮你工作效率提升100倍!希望能为大家派上用途!下面以图片&amp;文字的形式展现给大家!文字可以直接复制!图片也可以直接拿去收藏!..._快捷键可以帮助自己

用HTML语言制作一个非常浪漫的生日祝福网,手把手教你制作炫酷生日祝福网页_用html做一个生日快乐网页-程序员宅基地

文章浏览阅读2.2w次,点赞317次,收藏636次。明天就是女朋友的生日了, 是时候展现专属于程序员的浪漫了!你打算怎么给心爱的人表达爱意?鲜花礼物?代码表白?还是创意DIY?或者…无论那种形式,快来秀我们一脸吧!_用html做一个生日快乐网页

idea快捷键配置和常用快捷键_idea自定义快捷键-程序员宅基地

文章浏览阅读1.1k次。idea快捷键配置和常用快捷键_idea自定义快捷键

y2.2隐藏英雄密码_从嗨到2y 10 tmnkr您的密码发生了什么-程序员宅基地

文章浏览阅读99次。y2.2隐藏英雄密码Say that I decide to sign up for an account an incredibly insecure password, ‘hi’. How does this become something stored in the database like this: 假设我决定为一个帐户注册一个非常不安全的密码“ hi ”。 它如何变成这样存储在数据..._$2y$10$y

从0到1搭建一套属于你自己的高精度实时结构光3D相机(1):硬件搭建-程序员宅基地

文章浏览阅读1.6k次,点赞42次,收藏11次。在这篇博客中,博主将主要介绍结构光3D相机的硬件如何搭建,主要涉及到相机与投影仪的选型与配置。在开头,博主先给大家摘出一段语录:能从硬件层面解决的问题,就别死磕算法了。是的,能从硬件层面解决的问题,死磕算法是没有意义的。例如,当你评估自己的3D相机精度却发现始终达不到理想水平时,不要在那两三句代码上死磕,回头想想,是不是自己的硬件搭建的不好,选型选的不对。就博主经验而言,大部分做结构光3D相机没几年的小萌新们,都对相机与投影仪的硬件特性毫无理解。

推荐开源项目:Notion Zh-CN - 中文本地化版本-程序员宅基地

文章浏览阅读407次,点赞5次,收藏4次。推荐开源项目:Notion Zh-CN - 中文本地化版本项目地址:https://gitcode.com/Reamd7/notion-zh_CN项目简介Notion Zh-CN 是一个由开发者 Reamd7 主导的开源项目,它的目标是为流行的生产力工具 Notion 提供中文本地化的支持。Notion 是一款集文档管理、知识库、任务管理和团队协作于一体的平台,而 Notion Zh-CN ..._notion 开源吗

推荐文章

热门文章

相关标签