Debian Codegraph @

pymeasure/display/widgets/directory_widget.py

raw
1 #
2 # This file is part of the PyMeasure package.
3 #
4 # Copyright (c) 2013-2024 PyMeasure Developers
5 #
6 # Permission is hereby granted, free of charge, to any person obtaining a copy
7 # of this software and associated documentation files (the "Software"), to deal
8 # in the Software without restriction, including without limitation the rights
9 # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 # copies of the Software, and to permit persons to whom the Software is
11 # furnished to do so, subject to the following conditions:
12 #
13 # The above copyright notice and this permission notice shall be included in
14 # all copies or substantial portions of the Software.
15 #
16 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 # THE SOFTWARE.
23 #
24
25 import logging
26
27 from ..Qt import QtCore, QtGui, QtWidgets
28
29 log = logging.getLogger(__name__)
30 log.addHandler(logging.NullHandler())
31
32
33 class DirectoryLineEdit(QtWidgets.QLineEdit):
34 """
35 Widget that allows to choose a directory path.
36 A completer is implemented for quick completion.
37 A browse button is available.
38 """
39
40 def __init__(self, parent=None):
41 super().__init__(parent=parent)
42
43 completer = QtWidgets.QCompleter(self)
44 completer.setCompletionMode(QtWidgets.QCompleter.CompletionMode.PopupCompletion)
45
46 model = QtGui.QFileSystemModel(completer)
47 model.setRootPath(model.myComputer())
48 model.setFilter(QtCore.QDir.Filter.Dirs |
49 QtCore.QDir.Filter.Drives |
50 QtCore.QDir.Filter.NoDotAndDotDot |
51 QtCore.QDir.Filter.AllDirs)
52 completer.setModel(model)
53
54 self.setCompleter(completer)
55
56 browse_action = QtGui.QAction(self)
57 browse_action.setIcon(self.style().standardIcon(
58 getattr(QtWidgets.QStyle.StandardPixmap, 'SP_DialogOpenButton')))
59 browse_action.triggered.connect(self.browse_triggered)
60
61 self.addAction(browse_action, QtWidgets.QLineEdit.ActionPosition.TrailingPosition)
62
63 def _get_starting_directory(self):
64 current_text = self.text()
65 if current_text != '' and QtCore.QDir(current_text).exists():
66 return current_text
67
68 else:
69 return '/'
70
71 def browse_triggered(self):
72 path = QtWidgets.QFileDialog.getExistingDirectory(
73 self, 'Directory', self._get_starting_directory())
74 if path != '':
75 self.setText(path)