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

智能推荐

一个ngrok如何穿透多个端口?_ngrok多个端口-程序员宅基地

文章浏览阅读2.7k次,点赞2次,收藏4次。如何不充钱就可以穿透多个端口?./ngrok authtoken 授权码之前这个操作的生成的yml文件中修改 端口可添加多个addr:port端口可随意配置_ngrok多个端口

C语言 char转uint8_t-程序员宅基地

文章浏览阅读5.9k次。char转uint8_t:static int char2uint(char *input, uint8_t *output){ for(int i = 0; i < 24; i++) { output[i] &= 0x00; for (int j = 1; j >= 0; j--) { char hb = input[i*2 + 1 - j]; if (hb >= '0' &..._char转uint8_t

android 陀螺仪简单使用,判读手机是否静止状态_安卓陀螺仪多少才算静止-程序员宅基地

文章浏览阅读6.5k次,点赞5次,收藏13次。陀螺仪允许您在任何给定时刻确定Android设备的角速度。简单来说,它告诉您设备绕X,Y和Z轴旋转的速度有多快。最近,即使是预算手机正在制造,陀螺仪内置,增强现实和虚拟现实应用程序变得如此受欢迎。通过使用陀螺仪,您可以开发可以响应设备方向的微小更改的应用程序。创建陀螺仪对象和管理器manager// Register it, specifying the polling interv..._安卓陀螺仪多少才算静止

lib静态库逆向分析_libtersafe-程序员宅基地

文章浏览阅读4.7k次,点赞3次,收藏16次。当我们要分析一个lib库里的代码时,首先需要判断这是一个静态库还是一个导入库。库类型判断lib文件其实是一个压缩文件。我们可以直接使用7z打开lib文件,以查看里面的内容。如果里面的内容是obj文件,表明是静态库。如果里面的内容是dll文件,表明是导入库。导入库里面是不包含代码的,代码包含在对应的dll文件中。从lib中提取obj静态库是一个或者多个obj文件的打包,这里有两个方法从中提取obj:Microsoft 库管理器 7z解压Microsoft 库管理器(li_libtersafe

Linux的网络适配器_linux 查询网络适配器-程序员宅基地

文章浏览阅读5.3k次,点赞3次,收藏3次。了解一下,省的脑壳痛 桥接模式对应的虚拟网络名称“VMnet0” 桥接模式下,虚拟机通过主机的网卡进行通信,若物理主机有多块网卡(有线的和无线网卡),应选择桥结哪块物理网卡桥接模式下,虚拟机和物理主机同等地位,可以通过物理主机的网卡访问外网(局域网),一个局域网的其他计算机可以访问虚拟机。为虚拟机设置一个与物理网卡在同个网段的IP,则虚拟机就可以与物理主机以及局域..._linux 查询网络适配器

【1+X Web前端等级考证 】 | Web前端开发中级理论 (附答案)_1+xweb前端开发中级-程序员宅基地

文章浏览阅读3.4w次,点赞77次,收藏438次。# 前言2020 12月 1+X Web 前端开发中级 模拟题大致就更这么多,我的重心不在这里,就不花太多时间在这里面了。但是,说说1+X Web前端开发等级考证这个证书,总有人跑到网上问:这个证书有没有用? 这个证书含金量高不高?# 关于考不考因为这个是工信部从2019年才开始实施试点的,目前还在各大院校试点中,就目前情况来看,知名度并不是很高,有没有用现在无法一锤定音,看它以后办的怎么样把,软考以前也是慢慢地才知名起来。能考就考吧,据所知,大部分学校报考,基本不用交什么报考费(小部分学校,个别除._1+xweb前端开发中级

随便推点

项目组织战略管理及组织结构_项目组织的具体形态的是战略管理层-程序员宅基地

文章浏览阅读1.7k次。组织战略是组织实施各级项目管理,包括项目组合管理、项目集管理和项目管理的基础。只有从组织战略的高度来思考,思考各个层次项目管理在组织中的位置,才能够理解各级项目管理在组织战略实施中的作用。同时战略管理也为项目管理提供了具体的目标和依据,各级项目管理都需要与组织的战略保持一致。..._项目组织的具体形态的是战略管理层

图像质量评价及色彩处理_图像颜色质量评价-程序员宅基地

文章浏览阅读1k次。目录基本统计量色彩空间变换亮度变换函数白平衡图像过曝的评价指标多视影像因曝光条件不一而导致色彩差异,人眼可以快速区分影像质量,如何利用图像信息辅助算法判断影像优劣。基本统计量灰度均值方差梯度均值方差梯度幅值直方图图像熵p·log(p)色彩空间变换RGB转单通道灰度图像 mean = 225.7 stddev = 47.5mean = 158.5 stddev = 33.2转灰度梯度域gradMean = -0.0008297 / -0.000157461gr_图像颜色质量评价

MATLAB运用规则,利用辛普森规则进行数值积分-程序员宅基地

文章浏览阅读1.4k次。Simpson's rule for numerical integrationZ = SIMPS(Y) computes an approximation of the integral of Y via the Simpson's method (with unit spacing). To compute the integral for spacing different from one..._matlab利用幸普生计算积分

【AI之路】使用huggingface_hub优雅解决huggingface大模型下载问题-程序员宅基地

文章浏览阅读1.2w次,点赞28次,收藏61次。Hugging face 资源很不错,可是国内下载速度很慢,动则GB的大模型,下载很容易超时,经常下载不成功。很是影响玩AI的信心。经过多次测试,终于搞定了下载,即使超时也可以继续下载。真正实现下载无忧!究竟如何实现?且看本文分解。_huggingface_hub

mysql数据库查看编码,mysql数据库修改编码_查看数据库编码-程序员宅基地

文章浏览阅读3.5k次,点赞2次,收藏7次。其中 `DEFAULT CHARSET` 和 `COLLATE` 分别指定了表的默认编码和排序规则。其中 `DEFAULT CHARACTER SET` 指定了数据库的默认编码。其中 `Collation` 列指定了字段的排序规则,这也是字段的默认编码。此命令将更改表的默认编码和排序规则。此命令将更改字段的编码和排序规则。此命令将更改数据库的默认编码。_查看数据库编码

机器学习(十八):Bagging和随机森林_bagging数据集-程序员宅基地

文章浏览阅读1.3k次,点赞7次,收藏24次。本文深入探讨了集成学习及其在随机森林中的应用。对集成学习的基本概念、优势以及为何它有效做了阐述。随机森林,作为一个集成学习方法,与Bagging有紧密联系,其核心思想和实现过程均在文中进行了说明。还详细展示了如何在Sklearn中利用随机森林进行建模,并对其关键参数进行了解读,希望能帮助大家更有效地运用随机森林进行数据建模。_bagging数据集