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

智能推荐

强大的 Vim 主题配色方案 下载安装方法_gvim主题下载-程序员宅基地

文章浏览阅读5.7k次,点赞5次,收藏11次。如何使用vim配色方案?本文针对windows平台下的gvim,linux平台下如何修改配色方案请求自行搜索。点击【 到github下载配色方案】按钮,到github页面下载xxx.vim配色方案文件; 将xxx.vim配色文件copy到Vimvim74colors目录下(笔者vim版本为7.4,不同版本目录可能不同); 修改Vim_vimrc文件,修改colorscheme 配置项..._gvim主题下载

python执行javascript脚本文件_在Python中执行javascript-程序员宅基地

文章浏览阅读785次。在使用python抓取网页的过程中,有的时候需要执行某些简单的javascript,以获得自己需要的内容,例如执行js里面的document.write或者document.getElementById等。自己解析js代码显然有点吃力不讨好,因此最好能找到一些可以解析执行js的python库。google之可以找到三个候选者,分别是微软的ScriptControl,v8的python移植PyV8,..._wxpython运行javascript脚本

Ubuntu13.04(64bit)下用Wine安装百度云、360云、微云_wine 百度云-程序员宅基地

文章浏览阅读1.1w次,点赞4次,收藏2次。首先用安装好 wine 1.6.2: sudo a_wine 百度云

Linux磁盘格式化_linux格式化磁盘-程序员宅基地

文章浏览阅读1.7w次,点赞3次,收藏41次。Linux磁盘格式化_linux格式化磁盘

Zigbee联盟基础知识普及-程序员宅基地

文章浏览阅读1.2k次。做智能家居,还要了解ZigBee联盟,不是做好产品就好吗,与ZigBee联盟有什么关系?在具体说明这个问题之前,我们不妨先来了解一下ZigBee。ZigBee实际是一种短距离、低功耗的无线通信技术,名称来源于 ZigZag——一种蜜蜂的肢体语言。当蜜蜂新发现一片花丛后会用特殊舞蹈来告知同伴发现的食物种类及位置等信息,是蜜蜂群体间一种简单、高效的传递信息..._zigbee联盟

分段线性插值法matlab,matlab实现lagrange插值和分段线性插值-程序员宅基地

文章浏览阅读1.7k次。《matlab实现lagrange插值和分段线性插值》由会员分享,可在线阅读,更多相关《matlab实现lagrange插值和分段线性插值(4页珍藏版)》请在人人文库网上搜索。1、数值分析作业姓名:虞驰程题目:函数:fx=11+x2在-5,5上,取n=10,对其进行分段线性插值和拉格朗日插值,在Matlab中实现且绘图。Matlab实现:首先定义函数f,在Matlab中用function.m文件编...

随便推点

MMlab实验室AI实战营-人体姿态估计与MMPose_人体姿态估计直接回归方法流程-程序员宅基地

文章浏览阅读432次。当骨骼发生变化时,特定关节点的位置变化对人体表面不同顶点(Vertex)的位置变化有不同影响,在混合蒙皮技术里,这种影响是由不同的权重实现的。两个阶段的检测共用了一个图像特征网络,设计了Spatial Transform Network(STN)模块,从完整的特征图中裁剪出单人对应的图像特征,用于后续关键点检测。设计思路:准去的姿态估计需要结合不同尺度的信息:局部信息(检测不同的身体组件)、全局信息(建模组件之间的关系,在大尺度变形、遮挡时也可以准确推断出姿态)绝对坐标:各关节点在相机坐标系中的坐标;_人体姿态估计直接回归方法流程

Pytorch Dataloader 模块源码分析(二):Sampler / Fetcher 组件及 Dataloader 核心代码-程序员宅基地

文章浏览阅读712次。总算写完了 DataLoader 部分,总结这一块的源码主要是因为公司最近用到了相关的业务,需要对 Dataset 和 DataLoader 进行改造,因此认真读了这一部分的源码。总而言之,Dataset 和 DataLoader 模块为整个 Pytorch 提供了通用的数据加载和预处理接口,整体代码有很高的鲁棒性。如果说这个模块还有什么可以改进的地方,主要就在于 I/O 的部分,Dataset 在实现 shuffle 操作时,加载数据使用的是随机 I/O,这会大幅降低 I/O。...

Asp类型判断及数组打印-程序员宅基地

文章浏览阅读504次。ASP类型判断TypeName 函数返回一个字符串,提供有关变量的 Variant 子类型信息。TypeName(varname)必选项的 varname 参数,可以是任何变量。返回值TypeName 函数返回值如下:值 描述Byte 字节值Integer 整型值Long 长整型值Single 单精度浮点值Double 双精度浮点值Currency 货币值Dec...

Adroid Studio 2022.3.1 版本配置greendao提示无法找到_plugin with id 'org.greenrobot.greendao' not found-程序员宅基地

文章浏览阅读647次。之前报错,主要就是id 'org.greenrobot.greendao'这个包无法找到,找不到的原因就是org.greenrobot:greendao-gradle-plugin:3.3.1需要添加到整个项目模块的配置文件build.gradle(module)中,我一直在app配置文件。在配置greendao的过程中,在网上寻找各种方法去配置都显示错误:Plugin with id 'org.greenrobot.greendao' not found.中的添加的,所以一直无法找到。_plugin with id 'org.greenrobot.greendao' not found

esxi查看许可过期_解决Vsphere Client 60天过期问题-程序员宅基地

文章浏览阅读2.7k次。步骤:使用Vcenter client登陆试图---系统管理---许可---许可证秘钥右键----管理vsphere许可证秘钥,然后一步步添加。注册机:见百度云盘VMWare:vSphere6企业版参考序列号HV4WC-01087-1ZJ48-031XP-9A843NF0F3-402E3-MZR80-083QP-3CKM24F6FX-2W197-8ZKZ9-Y31ZM-1C3LZJZ2E9-6D..._esxi7过期了怎么办

CMake_cmake_module_path-程序员宅基地

文章浏览阅读2k次。查看变量cmake --help-variable CMAKE_MODULE_PATH常用变量CMAKE_MODULE_PATH查看变量后发现该变量默认为空,需要自己定义。这个变量用来定义自己的cmake模块所在的路径。如果工程比较复杂,有可能会自己编写一些cmake模块,这些cmake模块是随工程发布的,为了让cmake在处理CMakeLists.txt时找到这些模块,你需要通过SET指令将cmake模块路径设置一下。比如SET(CMAKE_MODULE_PATH,${PROJECT_SOUR_cmake_module_path

推荐文章

热门文章

相关标签