In this post, I'll go through the process of building a custom list widget in PyQt5 and using it to display Kubernetes pod information.
There are two different ways (AFAIK) to create a custom list item with PyQt5. Using QListView and QListWidget.
QListWidget is easy to use as you can build a widget using QDesigner and use it. QListView is more involved but it gives much more flexibility and better performance when dealing with a large number of items.
I decided to use QListWidget for now to quickly develop this proof of concept but considering that I may have to switch that out with QListView if performance becomes an issue.
Using QDesigner, here is a simple widget with some QLabels and organised in a simple layout.
QDesigner generates a .ui file which can be converted to python using pyuic5. I have a simple script which processes all the ui files and generates code in the target folder.
for i in `ls resources/ui/*.ui`; do FNAME=`basename $i ".ui"`; ./venv/bin/pyuic5 $i \> "kuberider/generated/$FNAME.py"; done
Now the widget code is generated, the following class inherits from QWidget and the generated class to setup the widget UI.
from PyQt5 import QtWidgets
from ..entities.model import KubePodItem
from ..generated.pod_item_widget import Ui_PodItemWidget
class PodItemWidget(QtWidgets.QWidget, Ui_PodItemWidget):
pod_info: KubePodItem
def __init__(self, pod_info: KubePodItem, parent=None):
super(PodItemWidget, self).__init__(parent)
self.setupUi(self)
self.set_data(pod_info)
def set_data(self, pod_info: KubePodItem):
self.pod_info = pod_info
self.lbl_pod_name.setText(pod_info.name)
self.lbl_pod_count.setText(pod_info.count)
self.lbl_pod_status.setText(pod_info.pod_status)
def get_data(self):
return self.pod_info
Along with the code to setup the UI in the constructor, it also contains a couple of helper methods to update the data in the widget based on the KubePodItem object.
The only thing left now is to connect with the event notifying that pods have been loaded so that we can populate the list widget. See this post for how events and signals are used in this application.
def on_pods_loaded(self, pods):
logging.info(f"on_pods_loaded: Displaying {len(pods)}")
self.view.clear()
for pod in pods:
pod_widget = PodItemWidget(pod, self.view)
pod_widget_item = QtWidgets.QListWidgetItem(self.view)
pod_widget_item.setSizeHint(pod_widget.sizeHint())
self.view.addItem(pod_widget_item)
self.view.setItemWidget(pod_widget_item, pod_widget)
That should be it. Here is how it looks like with few pods. It shows the pod name, current status of the pod and number of containers ready.
Top comments (0)