Warning

This section contains snippets that were automatically translated from C++ to Python and may contain errors.

QXmlStream Bookmarks Example#

Demonstrates how to read and write to XBEL files.

The QXmlStream Bookmarks example provides a reader for XML Bookmark Exchange Language (XBEL) files using Qt’s QXmlStreamReader class for reading, and QXmlStreamWriter class for writing the files.

../_images/xmlstreamexample-screenshot.png

XbelWriter Class Definition#

The XbelWriter class contains a private instance of QXmlStreamWriter , which provides an XML writer with a streaming API. XbelWriter also has a reference to the QTreeWidget instance where the bookmark hierarchy is stored.

class XbelWriter():

# public
    XbelWriter = explicit(QTreeWidget treeWidget)
    writeFile = bool(QIODevice device)
# private
    def writeItem(item):
    xml = QXmlStreamWriter()
    treeWidget = QTreeWidget()

XbelWriter Class Implementation#

The XbelWriter constructor accepts a treeWidget to initialize within its definition. We enable QXmlStreamWriter ‘s auto-formatting property to ensure line-breaks and indentations are added automatically to empty sections between elements, increasing readability as the data is split into several lines.

def __init__(self, treeWidget):
    self.treeWidget = treeWidget

    xml.setAutoFormatting(True)

The writeFile() function accepts a QIODevice object and sets it using setDevice(). This function then writes the document type definition(DTD), the start element, the version, and treeWidget's top-level items.

def writeFile(self, QIODevice device):

    xml.setDevice(device)
    xml.writeStartDocument()
    xml.writeDTD("<not DOCTYPE xbel>")
    xml.writeStartElement("xbel")
    xml.writeAttribute(XbelReader.versionAttribute(), "1.0")
    for i in range(0, treeWidget.topLevelItemCount()):
        writeItem(treeWidget.topLevelItem(i))
    xml.writeEndDocument()
    return True

The writeItem() function accepts a QTreeWidgetItem object and writes it to the stream, depending on its tagName, which can either be a “folder”, “bookmark”, or “separator”.

def writeItem(self, item):

    tagName = item.data(0, Qt.UserRole).toString()
    if tagName == "folder":
        folded = not item.isExpanded()
        xml.writeStartElement(tagName)
        xml.writeAttribute(XbelReader.foldedAttribute(), folded if yesValue() else noValue())
        xml.writeTextElement(titleElement(), item.text(0))
        for i in range(0, item.childCount()):
            writeItem(item.child(i))
        xml.writeEndElement()
     elif tagName == "bookmark":
        xml.writeStartElement(tagName)
        if not item.text(1).isEmpty():
            xml.writeAttribute(XbelReader.hrefAttribute(), item.text(1))
        xml.writeTextElement(titleElement(), item.text(0))
        xml.writeEndElement()
     elif tagName == "separator":
        xml.writeEmptyElement(tagName)

XbelReader Class Definition#

The XbelReader contains a private instance of QXmlStreamReader , the companion class to QXmlStreamWriter . XbelReader also contains a reference to the QTreeWidget that is used to group the bookmarks according to their hierarchy.

class XbelReader():

# public
    XbelReader(QTreeWidget treeWidget)
    read = bool(QIODevice device)
    errorString = QString()
    QString versionAttribute() { return "version"; }
    QString hrefAttribute() { return "href"; }
    QString foldedAttribute() { return "folded"; }
# private
    def readXBEL():
    def readTitle(item):
    def readSeparator(item):
    def readFolder(item):
    def readBookmark(item):
    createChildItem = QTreeWidgetItem(QTreeWidgetItem item)
    xml = QXmlStreamReader()
    treeWidget = QTreeWidget()
    folderIcon = QIcon()
    bookmarkIcon = QIcon()

XbelReader Class Implementation#

The XbelReader constructor accepts a QTreeWidget to initialize the treeWidget within its definition. A QStyle object is used to set treeWidget's style property. The folderIcon is set to Normal mode where the pixmap is only displayed when the user is not interacting with the icon. The SP_DirClosedIcon , SP_DirOpenIcon , and SP_FileIcon correspond to standard pixmaps that follow the style of your GUI.

def __init__(self, treeWidget):
    self.treeWidget = treeWidget

    style = treeWidget.style()
    folderIcon.addPixmap(style.standardPixmap(QStyle.SP_DirClosedIcon),
                         QIcon.Normal, QIcon.Off)
    folderIcon.addPixmap(style.standardPixmap(QStyle.SP_DirOpenIcon),
                         QIcon.Normal, QIcon.On)
    bookmarkIcon.addPixmap(style.standardPixmap(QStyle.SP_FileIcon))

The read() function accepts a QIODevice and sets it using setDevice() . The actual process of reading only takes place if the file is a valid XBEL 1.0 file. Note that the XML input needs to be well-formed to be accepted by QXmlStreamReader . Otherwise, the raiseError() function is used to display an error message. Since the XBEL reader is only concerned with reading XML elements, it makes extensive use of the readNextStartElement() convenience function.

def read(self, QIODevice device):

    xml.setDevice(device)
    if xml.readNextStartElement():
        if (xml.name() == "xbel"
            and xml.attributes().value(versionAttribute()) == "1.0") {
            readXBEL()
        else:
            xml.raiseError(QObject.tr("The file is not an XBEL version 1.0 file."))


    return not xml.error()

The errorString() function is used if an error occurred, in order to obtain a description of the error complete with line and column number information.

def errorString(self):

    return QObject.tr("%1\nLine %2, column %3")
            .arg(xml.errorString())
            .arg(xml.lineNumber())
            .arg(xml.columnNumber())

The readXBEL() function reads the name of a startElement and calls the appropriate function to read it, depending on whether if its a “folder”, “bookmark” or “separator”. Otherwise, it calls skipCurrentElement() . The Q_ASSERT() macro is used to provide a pre-condition for the function.

def readXBEL(self):

    Q_ASSERT(xml.isStartElement() and xml.name() == "xbel")
    while xml.readNextStartElement():
        if xml.name() == "folder":
            readFolder(0)
        elif xml.name() == "bookmark":
            readBookmark(0)
        elif xml.name() == "separator":
            readSeparator(0)
else:
            xml.skipCurrentElement()

The readTitle() function reads the bookmark’s title.

def readTitle(self, item):

    Q_ASSERT(xml.isStartElement() and xml.name() == "title")
    title = xml.readElementText()
    item.setText(0, title)

The readSeparator() function creates a separator and sets its flags. The text is set to 30 “0xB7”, the HEX equivalent for period. The element is then skipped using skipCurrentElement() .

def readSeparator(self, item):

    Q_ASSERT(xml.isStartElement() and xml.name() == "separator")
    separator = createChildItem(item)
    separator.setFlags(item.flags()  ~Qt.ItemIsSelectable)
    separator.setText(0, QString(30, '\xB7'))
    xml.skipCurrentElement()

MainWindow Class Definition#

The MainWindow class is a subclass of QMainWindow , with a File menu and a Help menu.

class MainWindow(QMainWindow):

    Q_OBJECT
# public
    MainWindow()
# public slots
    def open():
    def saveAs():
    def about():
#if !defined(QT_NO_CONTEXTMENU) and !defined(QT_NO_CLIPBOARD)
    def onCustomContextMenuRequested(pos):
#endif
# private
    def createMenus():
    treeWidget = QTreeWidget()

MainWindow Class Implementation#

The MainWindow constructor instantiates the QTreeWidget object, treeWidget and sets its header with a QStringList object, labels. The constructor also invokes createActions() and createMenus() to set up the menus and their corresponding actions. The statusBar() is used to display the message “Ready” and the window’s size is fixed to 480x320 pixels.

def __init__(self):

    labels = QStringList()
    labels << tr("Title") << tr("Location")
    treeWidget = QTreeWidget()
    treeWidget.header().setSectionResizeMode(QHeaderView.Stretch)
    treeWidget.setHeaderLabels(labels)
#if !defined(QT_NO_CONTEXTMENU) and !defined(QT_NO_CLIPBOARD)
    treeWidget.setContextMenuPolicy(Qt.CustomContextMenu)
    treeWidget.customContextMenuRequested.connect(
            self.onCustomContextMenuRequested)
#endif
    setCentralWidget(treeWidget)
    createMenus()
    statusBar().showMessage(tr("Ready"))
    setWindowTitle(tr("QXmlStream Bookmarks"))
    availableSize = screen().availableGeometry().size()
    resize(availableSize.width() / 2, availableSize.height() / 3)

The open() function enables the user to open an XBEL file using getOpenFileName() . A warning message is displayed along with the fileName and errorString if the file cannot be read or if there is a parse error.

def open(self):

    fileName =
            QFileDialog.getOpenFileName(self, tr("Open Bookmark File"),
                                         QDir.currentPath(),
                                         tr("XBEL Files (*.xbel *.xml)"))
    if fileName.isEmpty():
        return
    treeWidget.clear()
    file = QFile(fileName)
    if not file.open(QFile.ReadOnly | QFile.Text):
        QMessageBox.warning(self, tr("QXmlStream Bookmarks"),
                             tr("Cannot read file %1:\n%2.")
                             .arg(QDir.toNativeSeparators(fileName),
                                  file.errorString()))
        return

    reader = XbelReader(treeWidget)
    if not reader.read(file):
        QMessageBox.warning(self, tr("QXmlStream Bookmarks"),
                             tr("Parse error in file %1:\n\n%2")
                             .arg(QDir.toNativeSeparators(fileName),
                                  reader.errorString()))
    else:
        statusBar().showMessage(tr("File loaded"), 2000)

The saveAs() function displays a QFileDialog , prompting the user for a fileName using getSaveFileName() . Similar to the open() function, this function also displays a warning message if the file cannot be written to.

def saveAs(self):

    fileName =
            QFileDialog.getSaveFileName(self, tr("Save Bookmark File"),
                                         QDir.currentPath(),
                                         tr("XBEL Files (*.xbel *.xml)"))
    if fileName.isEmpty():
        return
    file = QFile(fileName)
    if not file.open(QFile.WriteOnly | QFile.Text):
        QMessageBox.warning(self, tr("QXmlStream Bookmarks"),
                             tr("Cannot write file %1:\n%2.")
                             .arg(QDir.toNativeSeparators(fileName),
                                  file.errorString()))
        return

    writer = XbelWriter(treeWidget)
    if writer.writeFile(file):
        statusBar().showMessage(tr("File saved"), 2000)

The about() function displays a QMessageBox with a brief description of the example.

def about(self):

   QMessageBox.about(self, tr("About QXmlStream Bookmarks"),
            tr("The <b>QXmlStream Bookmarks</b> example demonstrates how to use Qt's "
               "QXmlStream classes to read and write XML documents."))

In order to implement the open(), saveAs(), exit(), about() and aboutQt() functions, we connect them to QAction objects and add them to the fileMenu and helpMenu. The connections are as shown below:

def createMenus(self):

    fileMenu = menuBar().addMenu(tr("File"))
    QAction *openAct = fileMenu->addAction(tr("&Open..."), self.open)
    openAct.setShortcuts(QKeySequence.Open)
    QAction *saveAsAct = fileMenu->addAction(tr("&Save As..."), self.saveAs)
    saveAsAct.setShortcuts(QKeySequence.SaveAs)
    QAction *exitAct = fileMenu->addAction(tr("E&xit"), self.close)
    exitAct.setShortcuts(QKeySequence.Quit)
    menuBar().addSeparator()
    helpMenu = menuBar().addMenu(tr("Help"))
    helpMenu->addAction(tr("&About"), self.about)
    helpMenu->addAction(tr("About &Qt"), qApp.quit)

The createMenus() function creates the fileMenu and helpMenu and adds the QAction objects to them in order to create the menu shown in the screenshot below:

xmlstreamexample-filemenu1

xmlstreamexample-helpmenu2

def createMenus(self):

    fileMenu = menuBar().addMenu(tr("File"))
    QAction *openAct = fileMenu->addAction(tr("&Open..."), self.open)
    openAct.setShortcuts(QKeySequence.Open)
    QAction *saveAsAct = fileMenu->addAction(tr("&Save As..."), self.saveAs)
    saveAsAct.setShortcuts(QKeySequence.SaveAs)
    QAction *exitAct = fileMenu->addAction(tr("E&xit"), self.close)
    exitAct.setShortcuts(QKeySequence.Quit)
    menuBar().addSeparator()
    helpMenu = menuBar().addMenu(tr("Help"))
    helpMenu->addAction(tr("&About"), self.about)
    helpMenu->addAction(tr("About &Qt"), qApp.quit)

`` main()``

Function#

The main() function instantiates MainWindow and invokes the show() function.

if __name__ == "__main__":

    app = QApplication([])
    mainWin = MainWindow()
    mainWin.show()
    mainWin.open()
    sys.exit(app.exec())

See the XML Bookmark Exchange Language Resource Page for more information about XBEL files.

Example project @ code.qt.io