Chapter 5. Dialogs and Widgets

Most, if not all, GUI applications that are developed have to be supplemented with dialogs and widgets to enable different use cases and workflows for the user. Dialogs are usually small-sized windows with specific functionalities that aid the users with selecting or executing some operation. The most common examples of dialogs include the File Open dialog in many text and image editing applications, the Color Chooser dialog in various paint applications, and so on. In many GUI toolkits, the terms dialogs and widgets are used interchangeably. As a general difference, dialogs are the small windows whose main purpose is to establish a connection between the user and the program. We normally use dialog boxes to receive an input from the users or to represent an output or error message to the users. However, widgets are collections of the building blocks of the applications, such as buttons, check boxes, progress bars, and so on. This chapter will introduce you to some of the built-in dialogs and widgets that Qt provides us. Moving on, we will develop a customized Find dialog that will add to the text-editor program that we developed in Chapter 3, Main Windows and Layout Management. We will also develop a customized Analog Clock widget.

In this chapter, we will be covering the following topics:

  • Built-in dialogs
  • Custom dialogs
  • Widgets at a glance
  • Custom widgets
  • Implementation of MDI

Built-in dialogs

Qt provides a rich set of built-in dialogs. They are as follows:

  • QFileDilaog: This provides the user with a dialog that allows them to select files or directories
  • QErrorMessage: This provides the user with a dialog that displays error messages
  • QColorDialog: This provides the user with a dialog to specify or choose between colors
  • QPrintDialog: This provides the user with a dialog that aids in printer and printing configuration
  • QPageSetupDialog: This provides the user with a dialog that manages configuration for the page-related options on a printer
  • QWizard: This provides a dialog framework for wizards
  • QProgressDialog: This provides feedback on the progress of a slow operation
  • QPrintPreviewDialog: This provides a dialog to preview and configure page layouts for printer output
  • QMessageBox: This provides a dialog that is usually used to display modal information to the user requiring approval or cancellation
  • QInputDialog: This provides a simple convenience dialog to get a single value from the user
  • QFontDialog: This provides a dialog widget to select a font

In this section, we will discuss the implementations of some widely used widgets. A few of the widgets, such as QMessageBox, QFontDialog, and QErrorMessage, have already been introduced to you in some of the preceding chapters.

QFileDialog

The PySide.QtGui.QFileDialog class provides a dialog that allows users to select files or directories. It helps users to traverse the native file system in order to select one or many files or directories. The easy and best way to create a file dialog is to use the static functions that are provided by the QFileDialog class. A sample use of static function is given as follows:

fileName = QFileDialog.getOpenFileName(self, "Open Files", "c:/", "Text                                                              files(*.txt)")

In this example, the file dialog was created using a static getOpenFileName function. Initially, this function call will create a file dialog with the path mentioned in the third parameter of the function. The fourth parameter restricts the type of file that has to be shown in the dialog to open it. The first parameter takes the value of the parent to the dialog, and the second is used to display a title for the dialog. The filters that are represented in the fourth parameter can take multiple values depending on the type of file that is to be filtered. Please note that the values must be separated by a ;; delimiter. An example for the filter can look like the following line:

"Images (*.png *.jpg);; Text files (*.txt);; Word documents(*.doc)"

The following code shows an example to create the file dialog in a menu option. The program is self-explanatory and is based on the concepts that we saw in the third chapter of this book:

import sys
from PySide.QtGui import *
from PySide.QtCore import *

class MyFileDialog(QMainWindow):
    
    def __init__(self):
        QMainWindow.__init__(self)
        
        self.textEdit = QTextEdit()
        self.setCentralWidget(self.textEdit)
        self.statusBar()

        openFile = QAction(QIcon('open.png'), 'Open', self)
        openFile.setShortcut('Ctrl+O')
        openFile.setStatusTip('Open new File')
        openFile.triggered.connect(self.showDialog)

        menubar = self.menuBar()
        fileMenu = menubar.addMenu('&File')
        fileMenu.addAction(openFile)       
        
        self.setGeometry(300, 300, 350, 300)
        self.setWindowTitle('Example - File Dialog')
        self.show()
        
    def showDialog(self):
        fileName, _ = QFileDialog.getOpenFileName(self, "Open Text Files", "c:/", "Text files(*.txt)")
        
        contents = open(fileName, 'r')
        
        with contents:
            data = contents.read()
            self.textEdit.setText(data)
                                
        
if __name__ =='__main__':
    # Exception Handling
    try:
        myApp = QApplication(sys.argv)
        myFD = MyFileDialog()
        myFD.show()
        myApp.exec_()
        sys.exit(0)
    except NameError:
        print("Name Error:", sys.exc_info()[1])
    except SystemExit:
        print("Closing Window...")
    except Exception:
        print(sys.exc_info()[1]) 

Tip

If you run this program, you will witness that a file open dialog is opened on triggering the File->Open option in the menu bar.

The file dialog can also be created without using the static functions by directly creating an instance of the QFileDialog class that is explained, as follows:

  fileDialog = QFileDialog(self)
  fileDialog.setFileMode(QFileDialog.AnyFile)
  fileDialog.setNameFilter("Text files(*.txt)")

The second line of the preceding code sets the mode of the file dialog to Any File, which means that the user can specify a file that doesn't even exist in the filesystem. This mode is very useful when we want to create a Save As dialog. The other modes that the file dialog can take are as follows:

  • QFileDialog.ExistingFile: This is used if the user must select an existing file
  • QFileDialog.Directory: This is used if the user must select only a directory and not files
  • QFileDialog.ExistingFile: This is used if the user wants to select more than one file

The third line depicts how to set the filters for the file dialog as explained in the previous program. Also, the file dialog has two view modes, namely, View and Detail. As the name indicates, the list view just displays the name of the files and directories in a list, but the detail mode enhances it with additional details about the file, such as file size, date modified, and so on.

QInputDialog

The PySide.QtGui.QInputDialog class provides a very easy and convenient dialog to receive input from the users. The input can be a text string, a number, or an item from the list. A label is provided with the input box to indicate to the user what they have to enter. To enable this, four convenient functions are used, as follows:

  • QInputDialog.getText(): This receives a text or string from the user
  • QInputDialog.getInteger(): This receives an integer value as an input
  • QInputDialog.getDouble(): This receives a float value as an input with double-precision accuracy
  • QInputDialog.getItem(): This receives a particular selectable value from the list of items

The dialog is provided with two buttons, OK and Cancel, to accept or reject values respectively:

QInputDialog

The following code explains the use of various input dialogs:

# Import necessary modules
import sys
from PySide.QtGui import *
from PySide.QtCore import *

class MyInputDialog(QWidget):
    
    def __init__(self):        

        QWidget.__init__(self)
        self.myNameButton = QPushButton('Name', self)
        self.myNameButton.clicked.connect(self.showNameDialog)

        self.myAgeButton = QPushButton('Age', self)
        self.myAgeButton.clicked.connect(self.showAgeDialog)

        self.myChoiceButton = QPushButton('Choice', self)
        self.myChoiceButton.clicked.connect(self.showChoiceDialog)
        
        self.myNameLE = QLineEdit(self)
        self.myAgeLE = QLineEdit(self)
        self.myChoiceLE = QLineEdit(self)

        self.myLayout = QFormLayout()
        self.myLayout.addRow(self.myNameButton, self.myNameLE)
        self.myLayout.addRow(self.myAgeButton, self.myAgeLE)
        self.myLayout.addRow(self.myChoiceButton, self.myChoiceLE)
        
        self.setLayout(self.myLayout)    
        self.setGeometry(300, 300, 290, 150)
        self.setWindowTitle('Input Dialog Example')
        self.show()
        
    def showNameDialog(self):
        text, ok = QInputDialog.getText(self, 'Input Text Dialog', 
            'Enter your name:')
        
        if ok:
            self.myNameLE.setText(str(text))

    def showAgeDialog(self):
        text, ok = QInputDialog.getInteger(self, 'Input Number Dialog', 
            'Enter your age:')
        
        if ok:
            self.myAgeLE.setText(str(text))

    def showChoiceDialog(self):
        strList = ['Ice Cream', 'Choclates', 'Milk Shakes']
        text, ok = QInputDialog.getItem(self, 'Input Combo Dialog', 
            'Enter your choice:', strList)
        
        if ok:
            self.myChoiceLE.setText(str(text))
        
if __name__ =='__main__':
    # Exception Handling
    try:
        myApp = QApplication(sys.argv)
        myID = MyInputDialog()
        myID.show()
        myApp.exec_()
        sys.exit(0)
    except NameError:
        print("Name Error:", sys.exc_info()[1])
    except SystemExit:
        print("Closing Window...")
    except Exception:
        print(sys.exc_info()[1])

In the preceding code, each button's click event is connected to a slot that presents it to the user with different types of input dialogs. The values of the dialogs reflect on the Line Edit box upon clicking the OK button.

QColorDialog

The PySide.QtGui.QColorDialog provides a dialog to choose and specify colors. The color dialog is mainly used in the paint applications to allow the user to set the color of the brush or paint an area with a specific color. This dialog can also be used to set text colors in text-based applications. As with the other dialogs, we use a static QColorDialog.getColor() function to show the dialog and subsequently allow the user to select a color from the dialog. This dialog can also be used to allow the users to select the color transparency by passing some additional parameters. It is also possible to set and remember the custom colors and share them between color dialogs in an application. The code that follows is a short example of using the color dialog:

class MyColorDialog(QWidget):
    
    def __init__(self):
        QWidget.__init__(self)
        myColor = QColor(0, 0, 0) 

        self.myButton = QPushButton('Press to Change Color', self)
        self.myButton.move(10, 50)

        self.myButton.clicked.connect(self.showColorDialog)

        self.myFrame = QFrame(self)
        self.myFrame.setStyleSheet("QWidget { background-color: %s }" 
            % myColor.name())
        self.myFrame.setGeometry(130, 22, 100, 100)            
        
        self.setGeometry(300, 300, 250, 180)
        self.setWindowTitle('Color Dialog - Example')
        self.show()
        
    def showColorDialog(self):
      
        color = QColorDialog.getColor()

        if color.isValid():
            self.myFrame.setStyleSheet("QWidget { background-color: %s }"
                % color.name())

The preceding example will show a button that when pressed shows a color dialog. The color can be selected, and the same is painted in the frame that is used for this purpose.

QPrintDialog

The PySide.QtGui.QPrintDialog provides a dialog to specify the user's printer configuration. The configuration includes document-related settings, such as the paper size and orientation, type of print, color or grayscale, range of pages, and number of copies to print. The configuration settings also allow the user to select the type of printer from the printers that are available, including any configured network printers. The QPrintDialog objects are constructed with a PySide.QtGui.QPrinter object and executed using the exec_() function. The printer dialog uses the native system of display and configuration. The following example shows a crude way of creating a print dialog. The refined implementation is left as an exercise for you to explore. A sample implementation can be downloaded from the code snippets that come along with this book:

def printDoc(self):
        document = QTextDocument("Sample Page")
        printer = QPrinter()
  
        myPrintDialog = QPrintDialog(printer, self)
        if myPrintDialog.exec_() != QDialog.Accepted:
            return
       document.print_(printer)
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset