How can I customize the QCompleter popup window in PyQt?

4.3k views Asked by At

I have a few things for a QLineEdit's QCompleter I'm interested in customizing. I want to make it behave similar to the address / search bar in Chrome.

  1. How can I limit the number of rows that are displayed? For example, even if there are 15 matches, I only want the QCompleter to show 5.
  2. How can I resize the popup window? For example, I want to make the popup window nice and snug. As per the above example, I want the popup window to resize to 5 rows exactly without any showing any ugly scroll bars.
  3. How can I move the popup window? For example, I want to adjust the vertical position of the popup window so that it's slightly below the parent widget.
  4. How can I format the shown popup window's list items? For example, I want to bold the part of the word that is matching.
2

There are 2 answers

1
ekhumoro On BEST ANSWER
  1. To limit the number of rows: change the model to a QStringListModel using QCompleter.setModel, and set a fixed number of items before the popup is shown. Also ensure that maxVisibleItems is set appropriately (default is seven).
  2. The popup window should resize to the correct height automatically. The width of the popup can be calculated by adding together the width of the margins (popup.width() - popup.viewport().width()), the width of the frame (2 * popup.frameWidth()), and the width of the longest string (popup.fontMetrics().boundingRect(string).width()).
  3. The positioning (and width) of the popup can be controlled by passing an appropriate QRect to QCompleter.complete.
  4. The format of the list items could be controlled by setting an item delegate on the popup. See this answer for an example of a rich-text item delegate. (But note that this will effect how the popup width is calculated).
1
Neel Basu On

Though I've never tried the Same The Documentation Clearly States to use maxVisibleItems(int maxItem) to restrict number items visible.

and as with customization of the PopUp Window I thing You need to make a subclass of QAbstractItemView and pass it on QCompleter::setPopup(QAbstractItemView * popup)

set setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff)