Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

How to pass a Drawable to a QML element?



  • The requirement is to show Android app icons for a launcher. I tried the following JNI approach: First I transfer the Drawable to a Bitmap and from a Bitmapto a base64 encoded string:

    public static String drawableToBase64 (Drawable drawable) {
        Bitmap bitmap = null;
    
        if (drawable instanceof BitmapDrawable) {
            BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
            if(bitmapDrawable.getBitmap() != null) {
                bitmap = bitmapDrawable.getBitmap();
            }
        }
    
        if (bitmap == null) {
            if (drawable.getIntrinsicWidth() <= 0 || drawable.getIntrinsicHeight() <= 0) {
                bitmap = Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888); // Single color bitmap will be created of 1x1 pixel
            } else {
                bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
            }
    
            Canvas canvas = new Canvas(bitmap);
            drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
            drawable.draw(canvas);
        }
    
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
        byte[] imageBytes = baos.toByteArray();
    
        return Base64.encodeToString(imageBytes, Base64.DEFAULT);
    }
    

    In my QML file, I use the following paramter for the icon of a Button

    Button {
        icon.source: "data:image/png;base64," + base64string
        icon.width: parent.width * 0.35
        icon.height: parent.width * 0.35
        display: AbstractButton.TextUnderIcon
        ...
    }
    

    Some icons are working. For the most icons, I just can see a white square. I'm afraid converting images is a complex topic. Has someone a solution?

    Maybe I can write the Drawable into a temp directory and read them with a URL in the QML code.



  • I have the solution. I was only a single line. Everything was correct. I just had to add the following line to for the button:

    icon.color: "transparent"
    

    Crazy.



  • I have the solution. I was only a single line. Everything was correct. I just had to add the following line to for the button:

    icon.color: "transparent"
    

    Crazy.


Log in to reply