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

智能推荐

转贴:win2008改造成准VISTA-程序员宅基地

文章浏览阅读123次。安装WINDOWS SERVER 2008前请确认你已经做好了以下准备:1.你的硬件必须满足下列要求处理器:最小: 1GHz 建议: 2GHz 最佳: 3GHz 或者更快速的内存: 最小: 512MB RAM建议: 1GB RAM最佳: 2GB RAM (完整安装) 或者 1GB RAM (Server Core 安装) 或者最大 (32位系统 ): 4GB (标准版) 或..._net framework 3.0支持开vista玻璃效果吗

【正一专栏】巴萨四大皆空怎么办_巴萨14年四大皆空-程序员宅基地

文章浏览阅读2.5k次。巴萨四大皆空怎么办每年的四月对于双线作战的球队来说都是决定命运的时刻,巴萨神奇逆转大巴黎后不得不在欧冠面临着尤文图斯的挑战,而在国内联赛又要紧追领头羊皇马。一个月要踢9场比赛,基本上都是一周双赛。巴萨上周刚刚在联赛中输球,错失了反超皇马的机会,而今天凌晨的欧冠比赛,巴萨0:3惨败给尤文图斯,欧冠晋级之路前景黯淡、又只能期待奇迹。没了联赛和欧冠,巴萨就会四大皆空,恩里克只能黯然走_巴萨14年四大皆空

苹果系统使用linux内核,iOS操作系统是不是基于Linux呢?-程序员宅基地

文章浏览阅读5.2k次。iOS实际上是Darwin的ARM变体,源自BSD,类UNIX内核,以及Apple自己的Mach内核扩展系统。这与是完全不同的,Linux是一个单片内核,这意味着所有驱动程序代码和I / O工具包都是核心内核的一部分。Apple是一个混合内核。有些人住在内核中,有些是内核扩展(通常是.kext文件)。相比之下,Windows是一个微内核,意味着内核中的内容很少,而且几乎所有东西都是外部驱动程序。L..._苹果的ios系统是linux内核吗?

WEEX框架(一)框架简介和快速上手体验-程序员宅基地

文章浏览阅读8.6k次。框架简介Weex,是能够完美兼顾性能与动态性,让移动开发者通过简捷的前端语法写出Native级别的性能体验的框架,并支持iOS、安卓、Web等多端部署,由阿里巴巴研发和维护。对于移动开发者来说,Weex主要解决了频繁发版和多端研发两大痛点,同时解决了前端语言性能差和显示效果受限的问题。开发者只需要在自己的APP中嵌入Weex的SDK,就可以通过撰写HTML/CSS/JavaScript来开发Native级别的Weex界面。Weex界面的生成码其实就是一段很小的JS,可以像发布网页一样轻松部署在服务端,_weex框架

【工具使用系列】关于MATLAB for mac 运行时崩溃故障的解决方法_matlab_crash_dump-程序员宅基地

文章浏览阅读1.1w次。MATLAB 常见问题的解决方案1. MATLAB for mac使用过程中,突然崩溃……_matlab_crash_dump

PTA 5-10 多项式A除以B (2017cccc初赛L2-2)_pta你需要计算两个多项式相除的商q和余r,其中r的阶数必须小于b的阶数-程序员宅基地

文章浏览阅读2.7k次,点赞4次,收藏3次。5-10多项式A除以B(25分)这仍然是一道关于A/B的题,只不过A和B都换成了多项式。你需要计算两个多项式相除的商Q和余R,其中R的阶数必须小于B的阶数。输入格式:输入分两行,每行给出一个非零多项式,先给出A,再给出B。每行的格式如下:N e[1] c[1] ... e[N] c[N]其中N是该多项式非零项的个数,e[i]是第i个非零项的指数,c_pta你需要计算两个多项式相除的商q和余r,其中r的阶数必须小于b的阶数

随便推点

网络算法——基于堆的Prim算法和基于并查集的Kruskal算法_prim算法用并查集吗-程序员宅基地

文章浏览阅读386次。类名:Heapself.heap = list() 记录堆中的值 对应边的权重self.node = list() 记录堆中权重对应的起始节点self.neighbor = list() 记录堆中节点的邻接节点类方法:类方法作用definit_(self):初始化类defstr_(self):返回类的信息def将指定节点向上调整def将指定节点向下调整def拆入新节点def获取堆的最小值def更改指定节点的值类名:Union_Find。_prim算法用并查集吗

RuntimeError: Expected all tensors to be on the same device, but found at least two devices, cuda:1-程序员宅基地

文章浏览阅读4.5k次,点赞3次,收藏8次。一、了解nn.DataParallelhttps://zhuanlan.zhihu.com/p/102697821二、报错的几种原因2.1 cuda:0 and cpu!简单的将没有转移到gpu的参数转移即可。例如,xx.to("cuda")2.2 cuda:1 and cuda:0!可能存在有一些参数,不能使用nn.DataParallel自动分配到多个gpu。检查是否有自定义的tensor,注意:不能是Variable,必须是Parameter。..._on the same device, but found at least two devices, cuda:1

数组的两种传递方式_数组传递-程序员宅基地

文章浏览阅读1.3w次,点赞7次,收藏45次。 数组传递:将数组作为参数传递给函数,分值传递和地址传递。其中,值传递的效率较低,不建议使用。两种传递方式都会改变main函数中数组的值,如下代码中a[3]的结果都为6。注意区分数组的值传递和函数值传递的区别。//数组的两种传递方式#include&lt;iostream&gt;using namespace std;//值传递void fun1(int a[5]){ ..._数组传递

html点击按钮跳转到另一个界面_网页制作:一个简易美观的登录界面-程序员宅基地

文章浏览阅读2.2w次,点赞62次,收藏449次。效果图目录结构:在我们做一个页面之前,要先想好他的一个整体布局,也就是我们这里面的login.html主页面,大致结构如下:接下来,我们先上代码,看一下具体实现方法:login.html<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>..._html table登陆界面带有页面转换

C语言彩色版贪吃蛇——图形界面Easyx的简单使用_c easyx实现登录-程序员宅基地

文章浏览阅读2w次,点赞40次,收藏237次。大一上大概12月份学完了C语言,基本语法与知识已经基本具备,可以用C语言写出基本的贪吃蛇游戏,但是基础C语言的可视化与交互功能实在是太弱了,为了写出有色彩的游戏,需要在网上安装一个Easyx的插件,具体Easyx如何使用参见https://zhuanlan.zhihu.com/p/24826034点击打开链接然后编程软件我用的是VS 2017(因为Dev C++不支持Easyx) VS安装入口_c easyx实现登录

全球公链进展| Shibarium已上线;opBNB测试网PreContract硬分叉;Sui 主网 V1.7.1 版本_shibarium上线-程序员宅基地

文章浏览阅读1.6k次。Sui 主网现已升级至 V1.7.1 版本,此升级包含了多项修复和优化,包括:协议版本提升至 20 版本,在 Sui 框架中新增 Kiosk Extensions API 和一个新的 sui::kiosk_extension 模块,开发者可使用该 API 构建自定义的 Kiosk 应用程序,以扩展 Kiosk 基本功能;以太坊基金会工程师 Parithosh Jayathi 发推称,Dencun-devnet-8 已上线,这是开发者网络的最新迭代版本,旨在允许客户端与最新规范进行互操作性测试。_shibarium上线

推荐文章

热门文章

相关标签