scytheStudio / SCodes

This project is Qt & Qml wrapper for ZXing-C++ Library that is used for decoding 1D and 2D barcodes.
https://scythe-studio.com/
Apache License 2.0
107 stars 36 forks source link

App Crashes on "No camera detected" Error #31

Closed LeonnardoVerol closed 7 months ago

LeonnardoVerol commented 1 year ago

Without a camera on the Desktop, the code will try to access settings.at(0) but since there are no cameras, that index is invalid

on SBarcodeScanner

void SBarcodeScanner::initCam() {
    camera = new QCamera(this);

    const auto settings = camera->cameraDevice().videoFormats();

#ifdef Q_OS_ANDROID
    int i = camera->cameraDevice().videoFormats().size() - 1;
#else
    int i = 0;
#endif

    const auto s = settings.at(i); // Crash Point

    // ...
}

image

Easy workaround:

void SBarcodeScanner::initCam() {
    camera = new QCamera(this);

    if(camera->error())
    {
        qDebug() << "[SCodes] initCam() Failed: " << camera->errorString();
        return;
    }

    const auto settings = camera->cameraDevice().videoFormats();

   // ...
}
LeonnardoVerol commented 1 year ago

On top of that, you can add a new property and check If the camera is available on QML, to decide whether to use the "camera overlay scanning effect" or a text message:

on SBarcodeScanner

Q_PROPERTY(bool cameraAvailable READ cameraAvailable NOTIFY cameraAvailableChanged)
bool SBarcodeScanner::cameraAvailable() const
{
    return camera->isAvailable();
}

on QML

    Text {
        id: cameraNotAvailable
        visible: barcodeScanner.cameraAvailable === false

        width: parent.width
        anchors.centerIn: parent

        font.pointSize: 30
        font.letterSpacing: 2
        font.bold: true

        horizontalAlignment: Text.AlignHCenter
        wrapMode: Text.WordWrap

        text: qsTr("Camera Not Available")
    }

PS: you could also do the same to retrieve the actual "errorString"