binpress

Building a Text Editor with PyQt, Part 4: Tables, Dates and Unsaved Changes

Read part three here, or start from the beginning!

Welcome back to my series on Building a text editor with PyQt. In the last part, we started to add some great extensions such as a find-and-replace dialog and a way of inserting an images. This part will deal with two more extensions, namely one for inserting the current date and time and another for inserting and managing tables. Also, we’ll add a way of prompting the user about saving unsaved changes before closing Writer.

Inserting time and date

The time and date dialog isn’t very complicated. Create a new file in ext and call it datetime.py.

In ext/datetime.py:

  1. from PyQt4 import QtGui, QtCore
  2. from PyQt4.QtCore import Qt
  3.  
  4. from time import strftime
  5.  
  6. class DateTime(QtGui.QDialog):
  7.     def __init__(self,parent = None):
  8.         QtGui.QDialog.__init__(self, parent)
  9.  
  10.         self.parent = parent
  11.  
  12.         self.formats = ["%A, %d. %B %Y %H:%M",
  13.                         "%A, %d. %B %Y",
  14.                         "%d. %B %Y %H:%M",
  15.                         "%d.%m.%Y %H:%M",
  16.                         "%d. %B %Y",
  17.                         "%d %m %Y",
  18.                         "%d.%m.%Y",
  19.                         "%x",
  20.                         "%X",
  21.                         "%H:%M"]
  22.  
  23.         self.initUI()
  24.  
  25.     def initUI(self):
  26.  
  27.         self.box = QtGui.QComboBox(self)
  28.  
  29.         for i in self.formats:
  30.             self.box.addItem(strftime(i))
  31.  
  32.         insert = QtGui.QPushButton("Insert",self)
  33.         insert.clicked.connect(self.insert)
  34.  
  35.         cancel = QtGui.QPushButton("Cancel",self)
  36.         cancel.clicked.connect(self.close)
  37.  
  38.         layout = QtGui.QGridLayout()
  39.  
  40.         layout.addWidget(self.box,0,0,1,2)
  41.         layout.addWidget(insert,1,0)
  42.         layout.addWidget(cancel,1,1)
  43.  
  44.         self.setGeometry(300,300,400,80)
  45.         self.setWindowTitle("Date and Time")
  46.         self.setLayout(layout)
  47.  
  48.     def insert(self):
  49.  
  50.         # Grab cursor
  51.         cursor = self.parent.text.textCursor()
  52.  
  53.         datetime = strftime(self.formats[self.box.currentIndex()])
  54.  
  55.         # Insert the comboBox's current text
  56.         cursor.insertText(datetime)
  57.  
  58.         # Close the window
  59.         self.close()

In ext/__init__.py:

  1. __all__ = ["find","wordcount","datetime"]

Back to writer.py. In initToolbar():

  1.     dateTimeAction = QtGui.QAction(QtGui.QIcon("icons/calender.png"),"Insert current date/time",self)
  2.     dateTimeAction.setStatusTip("Insert current date/time")
  3.     dateTimeAction.setShortcut("Ctrl+D")
  4.     dateTimeAction.triggered.connect(datetime.DateTime(self).show)
  5.  
  6.     self.toolbar.addAction(dateTimeAction)

Very little code! In the constructor, __init__(), we again make our parent object a class member and also create a list of different time formats, which we’ll make use of in a bit. If you’re unfamiliar with these time and date parameters used by Python (originally C), you can find a description and list of them here.

Next up, initUI(). We create a QComboBoxself.box, and fill it with all of our time formats, which we turn into actual date and time strings using Python’s time.strftime() function. We also initialize a QPushButton for inserting the date and time string into the text and another button for canceling the operation. We connect the former to a slot function, self.insert(), and the latter very simply to the dialog’s close() method, which initiates your computer’s self-destruct sequence and blows it up after 60 seconds. Oh, wait, that’s self.detonate()self.close() just closes the window. In any case, we put all of these widgets into a layout again and configure some of the dialog’s basic settings such as size and window title.

In self.insert(), we first grab our QTextEdit‘s cursor and then get the appropriate format string using the QComboBox‘s currentIndex() method and our list of formats, which we then turn into a date-time string using strftime(). You might think that we could just use the QComboBox‘s currentText() method to retrieve the actual string and thus avoid a second call to strftime(), however the user might decide to make a sandwich just when he or she was about to press “insert” and thus the date-time string would not be up-to-date when the user returns – tragic. Once we have the new string, we insert it using our cursor’s insertText() method. Also, we want to close the dialog once the user has finished, so we call self.close() at the end.

The other two snippets of code should be self-explanatory if you’ve read the previous parts of this series. We add this module to our ext package and create an appropriate QAction for it in our main window.

Tables

Next up, I’ll show you how to create and manipulate tables. The steps to accomplish this are fairly straightforward:

  1. Go to your nearest forest and start choppin’ up some wood. I recommend a fine oak or fir tree for our purposes.
  2. Saw your wood into rectangular pieces

Huh? Oh, you mean a different kind of table? Oh right, tables for data! In that case, create a new file in our ext package called table.py:

ext/table.py:

  1. from PyQt4 import QtGui, QtCore
  2. from PyQt4.QtCore import Qt
  3.  
  4. class Table(QtGui.QDialog):
  5.     def __init__(self,parent = None):
  6.         QtGui.QDialog.__init__(self, parent)
  7.  
  8.         self.parent = parent
  9.  
  10.         self.initUI()
  11.  
  12.     def initUI(self):
  13.  
  14.         # Rows
  15.         rowsLabel = QtGui.QLabel("Rows: ",self)
  16.  
  17.         self.rows = QtGui.QSpinBox(self)
  18.  
  19.         # Columns
  20.         colsLabel = QtGui.QLabel("Columns",self)
  21.  
  22.         self.cols = QtGui.QSpinBox(self)
  23.  
  24.         # Cell spacing (distance between cells)
  25.         spaceLabel = QtGui.QLabel("Cell spacing",self)
  26.  
  27.         self.space = QtGui.QSpinBox(self)
  28.  
  29.         # Cell padding (distance between cell and inner text)
  30.         padLabel = QtGui.QLabel("Cell padding",self)
  31.  
  32.         self.pad = QtGui.QSpinBox(self)
  33.  
  34.         self.pad.setValue(10)
  35.  
  36.         # Button
  37.         insertButton = QtGui.QPushButton("Insert",self)
  38.         insertButton.clicked.connect(self.insert)
  39.  
  40.         # Layout
  41.         layout = QtGui.QGridLayout()
  42.  
  43.         layout.addWidget(rowsLabel,0,0)
  44.         layout.addWidget(self.rows,0,1)
  45.  
  46.         layout.addWidget(colsLabel,1,0)
  47.         layout.addWidget(self.cols,1,1)
  48.  
  49.         layout.addWidget(padLabel,2,0)
  50.         layout.addWidget(self.pad,2,1)
  51.  
  52.         layout.addWidget(spaceLabel,3,0)
  53.         layout.addWidget(self.space,3,1)
  54.  
  55.         layout.addWidget(insertButton,4,0,1,2)
  56.  
  57.         self.setWindowTitle("Insert Table")
  58.         self.setGeometry(300,300,200,100)
  59.         self.setLayout(layout)
  60.  
  61.     def insert(self):
  62.  
  63.         cursor = self.parent.text.textCursor()
  64.  
  65.         # Get the configurations
  66.         rows = self.rows.value()
  67.  
  68.         cols = self.cols.value()
  69.  
  70.         if not rows or not cols:
  71.  
  72.             popup = QtGui.QMessageBox(QtGui.QMessageBox.Warning,
  73.                                       "Parameter error",
  74.                                       "Row and column numbers may not be zero!",
  75.                                       QtGui.QMessageBox.Ok,
  76.                                       self)
  77.             popup.show()
  78.  
  79.         else:
  80.  
  81.             padding = self.pad.value()
  82.  
  83.             space = self.space.value()
  84.  
  85.             # Set the padding and spacing
  86.             fmt = QtGui.QTextTableFormat()
  87.  
  88.             fmt.setCellPadding(padding)
  89.  
  90.             fmt.setCellSpacing(space)
  91.  
  92.             # Inser the new table
  93.             cursor.insertTable(rows,cols,fmt)
  94.  
  95.             self.close()

ext/__init__.py:

  1. __all__ = ["find","datetime","wordcount","table"]

Back to writer.py. In initToolbar():

  1. tableAction = QtGui.QAction(QtGui.QIcon("icons/table.png"),"Insert table",self)
  2. tableAction.setStatusTip("Insert table")
  3. tableAction.setShortcut("Ctrl+T")
  4. tableAction.triggered.connect(table.Table(self).show)
  5.  
  6. self.toolbar.addAction(tableAction)

In initUI():

  1. # We need our own context menu for tables
  2. self.text.setContextMenuPolicy(Qt.CustomContextMenu)
  3. self.text.customContextMenuRequested.connect(self.context)

Below initUI():

  1. def context(self,pos):
  2.  
  3.         # Grab the cursor
  4.         cursor = self.text.textCursor()
  5.  
  6.         # Grab the current table, if there is one
  7.         table = cursor.currentTable()
  8.  
  9.         # Above will return 0 if there is no current table, in which case
  10.         # we call the normal context menu. If there is a table, we create
  11.         # our own context menu specific to table interaction
  12.         if table:
  13.  
  14.             menu = QtGui.QMenu(self)
  15.  
  16.             appendRowAction = QtGui.QAction("Append row",self)
  17.             appendRowAction.triggered.connect(lambda: table.appendRows(1))
  18.  
  19.             appendColAction = QtGui.QAction("Append column",self)
  20.             appendColAction.triggered.connect(lambda: table.appendColumns(1))
  21.  
  22.  
  23.             removeRowAction = QtGui.QAction("Remove row",self)
  24.             removeRowAction.triggered.connect(self.removeRow)
  25.  
  26.             removeColAction = QtGui.QAction("Remove column",self)
  27.             removeColAction.triggered.connect(self.removeCol)
  28.  
  29.  
  30.             insertRowAction = QtGui.QAction("Insert row",self)
  31.             insertRowAction.triggered.connect(self.insertRow)
  32.  
  33.             insertColAction = QtGui.QAction("Insert column",self)
  34.             insertColAction.triggered.connect(self.insertCol)
  35.  
  36.  
  37.             mergeAction = QtGui.QAction("Merge cells",self)
  38.             mergeAction.triggered.connect(lambda: table.mergeCells(cursor))
  39.  
  40.             # Only allow merging if there is a selection
  41.             if not cursor.hasSelection():
  42.                 mergeAction.setEnabled(False)
  43.  
  44.  
  45.             splitAction = QtGui.QAction("Split cells",self)
  46.  
  47.             cell = table.cellAt(cursor)
  48.  
  49.             # Only allow splitting if the current cell is larger
  50.             # than a normal cell
  51.             if cell.rowSpan() > 1 or cell.columnSpan() > 1:
  52.  
  53.                 splitAction.triggered.connect(lambda: table.splitCell(cell.row(),cell.column(),1,1))
  54.  
  55.             else:
  56.                 splitAction.setEnabled(False)
  57.  
  58.  
  59.             menu.addAction(appendRowAction)
  60.             menu.addAction(appendColAction)
  61.  
  62.             menu.addSeparator()
  63.  
  64.             menu.addAction(removeRowAction)
  65.             menu.addAction(removeColAction)
  66.  
  67.             menu.addSeparator()
  68.  
  69.             menu.addAction(insertRowAction)
  70.             menu.addAction(insertColAction)
  71.  
  72.             menu.addSeparator()
  73.  
  74.             menu.addAction(mergeAction)
  75.             menu.addAction(splitAction)
  76.  
  77.             # Convert the widget coordinates into global coordinates
  78.             pos = self.mapToGlobal(pos)
  79.  
  80.             # Add pixels for the tool and formatbars, which are not included
  81.             # in mapToGlobal(), but only if the two are currently visible and
  82.             # not toggled by the user
  83.  
  84.             if self.toolbar.isVisible():
  85.               pos.setY(pos.y() + 45)
  86.  
  87.             if self.formatbar.isVisible():
  88.                 pos.setY(pos.y() + 45)
  89.  
  90.             # Move the menu to the new position
  91.             menu.move(pos)
  92.  
  93.             menu.show()
  94.  
  95.         else:
  96.  
  97.             event = QtGui.QContextMenuEvent(QtGui.QContextMenuEvent.Mouse,QtCore.QPoint())
  98.  
  99.             self.text.contextMenuEvent(event)
  100.  
  101.     def removeRow(self):
  102.  
  103.         # Grab the cursor
  104.         cursor = self.text.textCursor()
  105.  
  106.         # Grab the current table (we assume there is one, since
  107.         # this is checked before calling)
  108.         table = cursor.currentTable()
  109.  
  110.         # Get the current cell
  111.         cell = table.cellAt(cursor)
  112.  
  113.         # Delete the cell's row
  114.         table.removeRows(cell.row(),1)
  115.  
  116.     def removeCol(self):
  117.  
  118.         # Grab the cursor
  119.         cursor = self.text.textCursor()
  120.  
  121.         # Grab the current table (we assume there is one, since
  122.         # this is checked before calling)
  123.         table = cursor.currentTable()
  124.  
  125.         # Get the current cell
  126.         cell = table.cellAt(cursor)
  127.  
  128.         # Delete the cell's column
  129.         table.removeColumns(cell.column(),1)
  130.  
  131.     def insertRow(self):
  132.  
  133.         # Grab the cursor
  134.         cursor = self.text.textCursor()
  135.  
  136.         # Grab the current table (we assume there is one, since
  137.         # this is checked before calling)
  138.         table = cursor.currentTable()
  139.  
  140.         # Get the current cell
  141.         cell = table.cellAt(cursor)
  142.  
  143.         # Insert a new row at the cell's position
  144.         table.insertRows(cell.row(),1)
  145.  
  146.     def insertCol(self):
  147.  
  148.         # Grab the cursor
  149.         cursor = self.text.textCursor()
  150.  
  151.         # Grab the current table (we assume there is one, since
  152.         # this is checked before calling)
  153.         table = cursor.currentTable()
  154.  
  155.         # Get the current cell
  156.         cell = table.cellAt(cursor)
  157.  
  158.         # Insert a new row at the cell's position
  159.         table.insertColumns(cell.column(),1)

First up, the Table class. This QDialog will allow the user to set initial configurations for the table he or she is about to insert into the text. This includes the number of rows and columns, as well as cell spacing, the distance between individual cells (similar to margin in CSS), and cell padding, the distance between the outer edge of a cell and its inner text (comparable to padding in CSS). We visualize these settings with a few labels indicating what the user is configuring (e.g. “Rows:”) and a QSpinBox each to input actual values for these parameters. Also, we create an “insert” button which the user presses to insert his or her table. We connect this QPushButton‘s clicked signal to a slot function, self.insert():

  1. # Rows
  2. rowsLabel = QtGui.QLabel("Rows: ",self)
  3.  
  4. self.rows = QtGui.QSpinBox(self)
  5.  
  6. # Columns
  7. colsLabel = QtGui.QLabel("Columns",self)
  8.  
  9. self.cols = QtGui.QSpinBox(self)
  10.  
  11. # Cell spacing (distance between cells)
  12. spaceLabel = QtGui.QLabel("Cell spacing",self)
  13.  
  14. self.space = QtGui.QSpinBox(self)
  15.  
  16. # Cell padding (distance between cell and inner text)
  17. padLabel = QtGui.QLabel("Cell padding",self)
  18.  
  19. self.pad = QtGui.QSpinBox(self)
  20.  
  21. self.pad.setValue(10)
  22.  
  23. # Button
  24. insertButton = QtGui.QPushButton("Insert",self)
  25. insertButton.clicked.connect(self.insert)

Afterwards, we add all of these widgets to a layout and set it as our dialog’s layout, as well as configure all the other necessary window settings already discussed before (window size, title etc.). In insert(), we grab our parent’s text cursor again and all of the values the user set for the various parameters on our dialog. Our cursor’s method for inserting a table is insertTable(), which takes the number of rows, the number of columns and optionally a QTextTableFormat object. If either the number of rows or the number of columns is zero, insertTable() does nothing. To prevent confusion, we check if rows or cols is zero and, if it is the case, pop up an error dialog. Else, we move on to inserting the table.

We can directly use the values we retrieved for row and column numbers, however we must use a QTextTableFormat object to make changes to cell padding and cell spacing. Therefore, we create a new QTextTableFormat and set the spacing and padding using setCellPadding() and setCellSpacing(), respectively. Finally, we use insertTable() method to insert the table and subsequently close the dialog:

  1.     def insert(self):
  2.  
  3.         cursor = self.parent.text.textCursor()
  4.  
  5.         # Get the configurations
  6.         rows = self.rows.value()
  7.  
  8.         cols = self.cols.value()
  9.  
  10.         if not rows or not cols:
  11.  
  12.             popup = QtGui.QMessageBox(QtGui.QMessageBox.Warning,
  13.                                       "Parameter error",
  14.                                       "Row and column numbers may not be zero!",
  15.                                       QtGui.QMessageBox.Ok,
  16.                                       self)
  17.             popup.show()
  18.  
  19.         else:
  20.  
  21.             padding = self.pad.value()
  22.  
  23.             space = self.space.value()
  24.  
  25.             # Set the padding and spacing
  26.             fmt = QtGui.QTextTableFormat()
  27.  
  28.             fmt.setCellPadding(padding)
  29.  
  30.             fmt.setCellSpacing(space)
  31.  
  32.             # Insert the new table
  33.             cursor.insertTable(rows,cols,fmt)
  34.  
  35.             self.close()

As you can see, the Table class is quite simple. The real fun starts back in writer.py. Before we get to that, though, don’t forget to add this module to __all__ in ext/__init__.py. Now, in writer.py, you’ll first need to create a QAction for the dialog in initToolbar() to make it accessible from the editor’s toolbar. I trust that this needs no further explaining by now.

With the code I discussed up to now, the user can insert a table into his or her document. The problem is, however, that PyQt’s tables aren’t very interactive. You can’t stretch or resize them and PyQt provides no way of adding or deleting rows and columns once the table has been initialized, also merging cells is impossible with these static tables. Therefore, we’ll create our own way of manipulating tables, which we accomplish by showing a custom context menu when the user right-clicks on a table. If the user right-clicks anywhere else, we’ll display the standard context menu again.

Here we go! In initUI(), we need to reset our QTextEdit‘s context menu policy, which we do by passing Qt.CustomContextMenu to the setContextMenuPolicy() method. By doing so, PyQt will no longer display its standard context menu when you right-click the QTextEdit and thus enable us to create our own menu. Next, connect the customContextMenuRequested() signal to a slot function, self.context():

  1. # We need our own context menu for tables
  2. self.text.setContextMenuPolicy(Qt.CustomContextMenu)
  3. self.text.customContextMenuRequested.connect(self.context)

In self.context(), we first grab our QTextEdit‘s QTextCursor again, which has a method for retrieving the table the cursor is currently over: currentTable(). If there is no table underneath the cursor, currentTable() returns zero, so we can check which context menu to call, our custom context menu for tables or the normal context menu for everything else. Just to get it out of the way, if there is no table, we call the standard context menu with the following code:

  1. event = QtGui.QContextMenuEvent(QtGui.QContextMenuEvent.Mouse,QtCore.QPoint())
  2.  
  3. self.text.contextMenuEvent(event)

Now, for our table-manipulation menu, we need to create a QMenu and populate it just like we did with our tool and menu bars. This means creating QActions and connecting their triggeredsignals to slot functions. We want actions for:

  • Appending rows and columns.
  • Removing rows and columns.
  • Inserting rows and columns.
  • Merging multiple cells into a single cell.
  • Splitting previously merged cells back into individual cells.

For the first set of actions responsible for appending rows or columns to the table, we don’t need to create separate slot methods. We just use one-line lambda expressions in which we call the table’s appendRows() or appendColumns() methods and pass it the number 1, to insert a single row or column, respectively:

  1. appendRowAction = QtGui.QAction("Append row",self)
  2. appendRowAction.triggered.connect(lambda: table.appendRows(1))
  3.  
  4. appendColAction = QtGui.QAction("Append column",self)
  5. appendColAction.triggered.connect(lambda: table.appendColumns(1))

The actions concerning removing and inserting rows and columns need a bit more code than a single line, so connect them to external slot functions:

  1. removeRowAction = QtGui.QAction("Remove row",self)
  2. removeRowAction.triggered.connect(self.removeRow)
  3.  
  4. removeColAction = QtGui.QAction("Remove column",self)
  5. removeColAction.triggered.connect(self.removeCol)
  6.  
  7.  
  8. insertRowAction = QtGui.QAction("Insert row",self)
  9. insertRowAction.triggered.connect(self.insertRow)
  10.  
  11. insertColAction = QtGui.QAction("Insert column",self)
  12. insertColAction.triggered.connect(self.insertCol)

Merging and splitting actions are a little special, as we’ll only want to make these actions accessible when they actually are of use.

First up, merging. After creating a QAction for it, we connect its signal to a lambda expression again, in which we call our table’s overloaded mergeCells() method. It requires us to pass it our cursor object and then takes care of merging selected cells, if there are any. We disable the action if the user’s cursor has no selection:

  1. mergeAction = QtGui.QAction("Merge cells",self)
  2. mergeAction.triggered.connect(lambda: table.mergeCells(cursor))
  3.  
  4. # Only allow merging if there is a selection
  5. if not cursor.hasSelection():
  6.     mergeAction.setEnabled(False)

For our action taking care of splitting merged cells, we need to, after creating a QAction for it, retrieve the cell of the table that has been right-clicked by the user. We do so by calling the table’s cellAt() method and passing it our cursor object. Then, we check if the row and column span of this cell is more than one, in which case it would have been previously merged with other cells. If so, we connect the triggered signal of our splitting action to a lambda expression again, in which we call our table’s splitCell() method.

We pass this method the merged cell’s row and column indices as well as the row and column spans of the to-be-split cells. By making the last two parameters one, we split the merged cells into individual cells again. I think this is the behavior most people would expect. You could, of course, pop up a question box where the user inserts the new span values, but I believe this will do fine for now. If the cell beneath the cursor has a row or column span of one, it hasn’t been merged so we disable the split action:

  1. splitAction = QtGui.QAction("Split cells",self)
  2.  
  3. cell = table.cellAt(cursor)
  4.  
  5. # Only allow splitting if the current cell is larger
  6. # than a normal cell
  7. if cell.rowSpan() > 1 or cell.columnSpan() > 1:
  8.  
  9.     splitAction.triggered.connect(lambda: table.splitCell(cell.row(),cell.column(),1,1))
  10.  
  11. else:
  12.     splitAction.setEnabled(False)

We then add all of these actions to our QMenu object and add separators between logically connected actions, such as between those handling appending rows/columns and those for removing:

  1. menu.addAction(appendRowAction)
  2. menu.addAction(appendColAction)
  3.  
  4. menu.addSeparator()
  5.  
  6. menu.addAction(removeRowAction)
  7. menu.addAction(removeColAction)
  8.  
  9. menu.addSeparator()
  10.  
  11. menu.addAction(insertRowAction)
  12. menu.addAction(insertColAction)
  13.  
  14. menu.addSeparator()
  15.  
  16. menu.addAction(mergeAction)
  17. menu.addAction(splitAction)

One tricky issue with creating custom context menus is positioning them. As you may have noticed, our self.context() method has a second parameter, pos. PyQt passes us a QPoint object which holds the coordinates of where the user right-clicked in our QTextEdit. However, there is one big problem: this QPoint PyQt hands us doesn’t take our tool and format bars into account! The table cell may be positioned at (0,0) within the QTextEdit but in terms of window coordinates, its real coordinates are in fact (0,90), as our toolbars, if not customized, are 45 pixels long.

To solve these problems, we need to check whether the toolbars are visible, as the user may have toggled their visibility, and add 45 pixels per visible toolbar to our QPoint object’s y coordinate. Also, we need to convert the coordinates from QTextEdit coordinates to global ones, which we achieve via our window’s mapToGlobal() method. We then re-position our menu with its move() method and finally display it by calling show():

  1. # Convert the widget coordinates into global coordinates
  2. pos = self.mapToGlobal(pos)
  3.  
  4. # Add pixels for the tool and format bars, which are not included
  5. # in mapToGlobal(), but only if the two are currently visible and
  6. # not toggled by the user
  7.  
  8. if self.toolbar.isVisible():
  9.     pos.setY(pos.y() + 45)
  10.  
  11. if self.formatbar.isVisible():
  12.     pos.setY(pos.y() + 45)
  13.  
  14.  
  15. # Move the menu to the new position
  16. menu.move(pos)
  17.  
  18. menu.show()

That’s it for context(). Let’s move on to the slot functions we connected our context menu actions to. They’re fairly similar to each other, so I’ll just discuss one. In removeRow(), the method that removes the row the user’s cursor is over, we grab our QTextEdit‘s cursor, the cursor’s current table and the table’s current cell. We then remove the row by calling the table’s removeRows()method and passing it the cell’s row() number along with the number 1, thus removing only the current row (passing a higher number removes n rows starting at the cell’s row index):

  1. def removeRow(self):
  2.  
  3.     # Grab the cursor
  4.     cursor = self.text.textCursor()
  5.  
  6.     # Grab the current table (we assume there is one, since
  7.     # this is checked before calling)
  8.     table = cursor.currentTable()
  9.  
  10.     # Get the current cell
  11.     cell = table.cellAt(cursor)
  12.  
  13.     # Delete the cell's row
  14.     table.removeRows(cell.row(),1)

The other slot methods only differ in the functions we call, I’m sure you’ll understand them. That’s it for tables!

A final add-on

After finishing part one of this series, I noticed that there was no way of prompting the user about saving a modified document before closing it. Let’s change that. In writer.py:

In __init__(), add this:

  1. self.changesSaved = True

In initUI(), add this:

  1. self.text.textChanged.connect(self.changed)

Below initUI:

  1. def changed(self):
  2.     self.changesSaved = False
  3.  
  4. def closeEvent(self,event):
  5.  
  6.     if self.changesSaved:
  7.  
  8.         event.accept()
  9.  
  10.     else:
  11.  
  12.         popup = QtGui.QMessageBox(self)
  13.  
  14.         popup.setIcon(QtGui.QMessageBox.Warning)
  15.  
  16.         popup.setText("The document has been modified")
  17.  
  18.         popup.setInformativeText("Do you want to save your changes?")
  19.  
  20.         popup.setStandardButtons(QtGui.QMessageBox.Save    |
  21.                                   QtGui.QMessageBox.Cancel |
  22.                                   QtGui.QMessageBox.Discard)
  23.  
  24.         popup.setDefaultButton(QtGui.QMessageBox.Save)
  25.  
  26.         answer = popup.exec_()
  27.  
  28.         if answer == QtGui.QMessageBox.Save:
  29.             self.save()
  30.  
  31.         elif answer == QtGui.QMessageBox.Discard:
  32.             event.accept()
  33.  
  34.         else:
  35.             event.ignore()

At the end of self.save(), insert this line:

  1. self.changesSaved = True

In __init__(), we create a new class member, self.changesSaved, that’ll store a boolean indicating whether or not the current document’s changes have been saved or not. Then, in initUI(), we connect our QTextEdit‘s textChanged signal to a slot function, self.changed(), in which we set our self.changesSaved member to False, signifying that there are unsaved modifications. We can’t use a lambda expression for this slot function, as you can’t assign anything in a lambda expression.

Next, we need to re-define our window’s closeEvent() method which takes a QCloseEvent as its only argument. This function will be called when the user attempts to close the window. Normally this method just calls the QCloseEvent‘s accept() method, which then closes the window. In our case, however, we want to check if there are any unsaved modifications to the document. If not, we also call event.accept() and just close our application. If there are changes, however, we’ll want to inform the user about this, which we do by popping up a message box.

Therefore, we create a QMessageBox object, give it an icon like we did for the table dialog’s message box, set its “headline” text using the setText() method and add some further clarification using setInformativeText(). We then give this dialog some buttons using the setStandardButtons() method, namely one for saving the document, one for canceling the closing of the window and one for discarding the changes and closing the document without saving. After displaying the message box by calling its exec_() method, which returns the user’s choice, we act accordingly by either saving the document, discarding changes by accepting the event or aborting the closing of the window by calling the event’s ignore() method.

Lastly, we set the self.changesSaved variable to True in the self.save() method, ensuring that the message box doesn’t pop if the user has already saved his or her changes.

Thank you

That’s it for this part and, unfortunately, also for this series on Building a text editor with PyQt. I hope you learned a lot and enjoyed building this text editor with me!

But hey, who says it should end here? There’s so much potential! If you have any ideas or suggestions on how to improve Writer, don’t hesitate to fork or clone this project on GitHub. Change its layout, add some color, improve features and add a few of your own!

Cheers!

Author: Peter Goldsborough

Scroll to Top