PyQt6 GUI Icon Generator App Part 2
Welcome to part 2 of our PyQt6 GUI Icon Generator App tutorial! In the previous article, we discussed how to set up the basic structure of the app and create a simple user interface. In this article, we will continue building on that foundation and add more functionality to the app.
Adding Image Upload Feature
One of the key features of an icon generator app is the ability to upload an image and convert it into an icon. We will add a button that allows users to upload an image file from their computer. To do this, we will use the QFileDialog class that provides a file dialog for selecting files.
import sys
from PyQt6.QtWidgets import QApplication, QMainWindow, QPushButton, QFileDialog
class IconGeneratorApp(QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.setWindowTitle("Icon Generator App")
self.setGeometry(100, 100, 400, 300)
upload_btn = QPushButton("Upload Image", self)
upload_btn.clicked.connect(self.showFileDialog)
self.show()
def showFileDialog(self):
options = QFileDialog.Options()
file_path, _ = QFileDialog.getOpenFileName(self, "Select Image", "", "Image Files (*.jpg *.png)", options=options)
if file_path:
print("Selected image file:", file_path)
if __name__ == "__main__":
app = QApplication(sys.argv)
app.setStyle("Fusion")
icon_generator_app = IconGeneratorApp()
sys.exit(app.exec())
In the above code, we have added a QPushButton called upload_btn to the main window. When the button is clicked, it calls the showFileDialog method which opens a file dialog for selecting an image file. The selected file path is then printed to the console.
Displaying Selected Image
Once the user selects an image file, we want to display the image in the app so they can preview how the icon will look. To do this, we will add a QLabel widget to the main window and set the image as its pixmap.
from PyQt6.QtGui import QPixmap
from PyQt6.QtWidgets import QLabel
# Inside the IconGeneratorApp class
self.image_label = QLabel(self)
self.image_label.setGeometry(20, 50, 200, 200)
pixmap = QPixmap(file_path)
self.image_label.setPixmap(pixmap)
self.image_label.setScaledContents(True)
In the above code, we have created a QLabel widget called image_label and set its pixmap to the selected image file. We also set the scaledContents property to True so that the image automatically scales to fit the label. Now, when the user uploads an image, it will be displayed in the app.
Conclusion
With the addition of the image upload feature and the ability to display the selected image, our PyQt6 GUI Icon Generator App is starting to take shape. In the next article, we will continue adding more functionality to the app, such as resizing the image to create the final icon. Stay tuned for more updates!