In this lesson we want to learn about Python PySide6 QColorDialog & QFontDialog.
PySide6 QColorDialog
QColorDialog is dialog box that allows the user to select a color. this is an example of how to use QColorDialog in PySide6:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
from PySide6.QtWidgets import QApplication,QVBoxLayout, QPushButton, QColorDialog import sys class Example(QPushButton): def __init__(self): super().__init__() vbox = QVBoxLayout() btn = QPushButton("Select Color") btn.clicked.connect(self.showDialog) vbox.addWidget(btn) self.setLayout(vbox) def showDialog(self): # show the QColorDialog color = QColorDialog.getColor() # set the button background color to the selected color if color.isValid(): self.setStyleSheet('background-color: {}'.format(color.name())) if __name__ == '__main__': app = QApplication(sys.argv) ex = Example() ex.show() sys.exit(app.exec()) |
In this example we have created QPushButton and set its label to “Select Color”. when the button is clicked we show QColorDialog using the getColor() method. we then set background color of the button to the selected color using the setStyleSheet() method.
Run the complete code and this will be the result.
PySide6 QFontDialog
QFontDialog is dialog box that allows the user to select a font. this is an example of how to use QFontDialog in PySide6:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
from PySide6.QtWidgets import QApplication, QPushButton, QFontDialog, QLabel, QVBoxLayout, QWidget from PySide6.QtGui import QFont import sys class Example(QWidget): def __init__(self): super().__init__() # create a QLabel and a QPushButton self.label = QLabel('Hello, World!', self) self.button = QPushButton('Select Font', self) self.button.clicked.connect(self.showDialog) # create a QVBoxLayout and add the label and button to it layout = QVBoxLayout(self) layout.addWidget(self.label) layout.addWidget(self.button) self.show() def showDialog(self): # show the QFontDialog font, ok = QFontDialog.getFont() # if the user clicked OK, set the label font to the selected font if ok: self.label.setFont(font) if __name__ == '__main__': app = QApplication(sys.argv) ex = Example() sys.exit(app.exec()) |
In this example we have created QLabel with the text “Hello, World!” and QPushButton with the label “Select Font”. when the button is clicked we show the QFontDialog using the getFont() method. we then set the font of the label to the selected font using the setFont() method.
Both QColorDialog and QFontDialog can be easily customized to suit the needs of your application. they are simple to use and can greatly enhance the user experience of your application.
Run the complete code and click on the button this will b the result.