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

智能推荐

详解冬奥冠军背后的AI黑科技-程序员宅基地

文章浏览阅读3.6k次。用人工智能普惠体育发展。

form表单提交的几种方式_提交表单-程序员宅基地

文章浏览阅读10w+次,点赞92次,收藏495次。表单提交方式一:直接利用form表单提交html页面代码:<!DOCTYPE html><html><head><meta charset="UTF-8" /><title>Insert title here</title></head><body><form action="h..._提交表单

Unity Spine SkeletonGraphic 动画重复播放 过度残影透明渐变Bug 解决方案_unity skeletongraphic-程序员宅基地

文章浏览阅读5.1k次。Unity Spine SkeletonGraphic 重复播放 过度残影Bug 解决方案不推荐使用SetToSetupPose和Setup Pose相关,代码直接贴上/// <summary>/// Spine播放设置/// </summary>/// <param name="trackIndex">填写0</param>/// <param name="animationName">动画名</param>/// &l_unity skeletongraphic

高斯分布3——边缘概率与条件概率_高斯分布的条件概率-程序员宅基地

文章浏览阅读3.5k次。一、推导过程:二、结果:边缘分布x1,x2 各自依然服从 μi,写反差矩阵 Σii 的多元高斯分布;条件概率分布给定 xj 求 xi 的分布:μi|j=μi+ΣijΣ−1jj(xj−μj)Σi|j=Σjj−ΣTijΣ−1iiΣij..._高斯分布的条件概率

Ratelimitcache: Python缓存库,支持速率限制-程序员宅基地

文章浏览阅读339次,点赞8次,收藏8次。Ratelimitcache: Python缓存库,支持速率限制项目链接: https://gitcode.com/simonw/ratelimitcache?utm_source=artical_gitcode如果你正在寻找一个Python缓存库,并且希望对缓存操作进行速率限制,那么Ratelimitcache可能是你的理想选择。什么是Ratelimitcache?Ratelimitca..._python ratelimit基于什么

【爬虫】Xpath和CSS信息提取的方法异同点_xpath 获取css-程序员宅基地

文章浏览阅读2.3k次,点赞2次,收藏8次。Xpath和CSS信息提取的方法异同点_xpath 获取css

随便推点

基于OFDM+64QAM系统的载波同步matlab仿真,输出误码率,星座图,鉴相器,锁相环频率响应以及NCO等-程序员宅基地

文章浏览阅读454次。正交频分复用(OFDM)是一种在现代通信系统中广泛使用的调制技术,它具有高效的频谱利用和抗多径衰落等特点。64QAM(64-ary Quadrature Amplitude Modulation)是一种调制方式,可以在每个符号中传输更多的位信息。在OFDM系统中,保持载波同步对确保数据传输的可靠性至关重要。_基于ofdm+64qam系统的载波同步matlab仿真,

Springboot毕设项目超市商品销售管理系统37x2w(java+VUE+Mybatis+Maven+Mysql)_vue+springboot+mybatis商品管理系统-程序员宅基地

文章浏览阅读67次。Jdk1.8 + Tomcat8.5 + Mysql + HBuilderX(Webstorm也行)+ Eclispe(IntelliJ IDEA,Eclispe,MyEclispe,Sts都支持)。若包含,则为maven项目,否则为非maven项目。Springboot毕设项目超市商品销售管理系统37x2w(java+VUE+Mybatis+Maven+Mysql)Springboot + mybatis + Maven + Vue 等等组成,B/S模式 + Maven管理等等。其他版本理论上也可以。_vue+springboot+mybatis商品管理系统

关掉\禁用win7自动配置ipv4地址的方法 默认网关自动消失的解决办法_禁止修改网关命令-程序员宅基地

文章浏览阅读3w次,点赞2次,收藏4次。转载自: http://blog.csdn.net/zouqin369/article/details/6913692 今天去公司设置好IP后,无论怎么样都上不了internet,再次打开本地后发现默认网关自动消失,cmd下输入ipconfig后的现象如下: 物理地址. . . . . . . . . . . . . : 00-22-64-55-76-8F DHCP 已启用_禁止修改网关命令

Extjs4.2 window加载HTML,父子页面html传参_extjs中打开网页怎么传参-程序员宅基地

文章浏览阅读482次。Extjs的窗口是可以加载自己的HTML的,但这样两个页面就相当独立了,传参是个问题 ,网上也没有很好的解答清楚,猫猫今天就说清楚这个模式的传参要点。_extjs中打开网页怎么传参

计算机网络复习——Ch3点到点数据链路层_hdlc go-back-n-程序员宅基地

文章浏览阅读1.2k次。Ch3点到点数据链路层知识点1. 点到点数据链路层要解决的主要问题2. 常见的帧管理(帧定界)方法3. CRC的计算4. 流量控制的基本原理5. 常见错误及其处理机制6. 滑动窗口的概念、形式及工作原理7. ARQ(Automatic Repeat reQuest)协议工作原理:8. 连续ARQ(Go-back-N ARQ)工作原理(特别注意累计确认):9. 选择重传ARQ工作原理10. 了解(高..._hdlc go-back-n

推荐文章

热门文章

相关标签