List Running Processes in a QListWidget

List running processes

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import sys
import psutil

from PySide6.QtCore import Slot, Qt
from PySide6.QtWidgets import (QApplication, QWidget,
    QVBoxLayout, QListWidget, QListWidgetItem, QLabel)


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

        super().__init__()
        
        layout = QVBoxLayout()
        self.setLayout(layout)
        
        # 1. Create a QListWidget

        self.list_widget = QListWidget()
        
        # 2. Use psutil to get the process list
        #    and add them to the list widget
        
        for process in psutil.process_iter(attrs=['pid', 'name', 'exe']):
            try:
                item = QListWidgetItem(f'{process.pid}: {process.name()}')
                item.setData(Qt.ItemDataRole.UserRole, process.exe())
                self.list_widget.addItem(item)
            except Exception as e:
                print(e)

        self.label = QLabel()
        
        # 3. Add the list widget to the window
        
        layout.addWidget(self.list_widget)
        layout.addWidget(self.label)

        self.list_widget.currentItemChanged.connect(
            self.on_current_item_changed)
    
    # 4. Optionally, display additional information
    #    about the selected process item. 
    
    def on_current_item_changed(self, current, previous):
        self.label.setText(current.data(Qt.ItemDataRole.UserRole))


if __name__ == '__main__':

    app = QApplication(sys.argv)

    main_window = Window()
    main_window.show()

    sys.exit(app.exec())

The psutil Python module lets you get various information about your operating system and, among other things, you can use it to list the running processes on your machine. To use psutil to list the currently active processes in a QListWidget

  1. Create a QListWidget object.

  2. Use psutil.process_iter() to get the running processes. For each process create a QListWidgetItem instance and set its text to the process name. Use QListWidgetItem.setData() to add additional information about the process to the QListWidgetItem setting the data role to the Qt.ItemDataRole.UserRole constant.

  3. Add the list widget object to the window layout.

  4. Optionally, display the additional data about a process when the user clicks on its item.