Python Qt: Saving images, and message popup dialog boxes

in #programming6 years ago

Screenshot from 2018-06-12 12-04-27.png

Previously in my image viewer application we made a feature for rotating images. That is fine for viewing, but next time you load the image you will need to rotate again.

What we need to do is save the modified image. For simplicity, we will simply overwrite the file, and then pop up a status message to say if it was successful.

Saving Image Files in Qt

Qt makes it easy to save the file away, and if you are happy with the defaults, you just need the filename.

You do have the option of saving in a different format or different quality, but I am happy to simply overwrite the image file and infer the format from the filename.

The save function returns success or failure, so we will keep that for the next step.

# overwrite save
def save_picture():
    global window, file, files, index, label
    file = files[index]
    picture = label.pixmap()
    success = picture.save(file)

Popup Dialog Message Boxes

If the save is successful, we will want to show that to the user. Feedback is an important part of user experience and usability.

Consider what would happen if we did not respond? The user would either keep mashing the save button, or might hit save and then close, but not realize the file had not saved due to file permissions or some disk issue.

The Qt dialog can simply show a message and an 'ok' button, so this is what we do.

There is also an input box, so we could have a "Save As" later.

    # message dialog
    dialog = QMessageBox(window)
    print(success)
    if success:
        dialog.setText("Image file saved as {}.".format(file))
    else:
        dialog.setText("Image can not be saved as {}.".format(file))

    dialog.exec_()

Save button

As before, we need to supply a button, but unlike previous examples, I use the & symbol to tell Qt the keyboard shortcut is Alt-S.

save = QPushButton("&Save", window)
save.clicked.connect(save_picture)

makerhacks.png

Coin Marketplace

STEEM 0.39
TRX 0.12
JST 0.040
BTC 70118.22
ETH 3546.28
USDT 1.00
SBD 4.89