multiselectwidget.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. from PyQt5 import QtCore, QtWidgets # pylint: disable=import-error
  2. from . import ui_multiselectwidget # pylint: disable=no-name-in-module
  3. class MultiSelectWidget(
  4. ui_multiselectwidget.Ui_MultiSelectWidget, QtWidgets.QWidget):
  5. selectedChanged = QtCore.pyqtSignal()
  6. itemsAdded = QtCore.pyqtSignal(list)
  7. itemsRemoved = QtCore.pyqtSignal(list)
  8. def __init__(self, parent=None):
  9. super(MultiSelectWidget, self).__init__(parent)
  10. self.setupUi(self)
  11. self.add_selected_button.clicked.connect(self.add_selected)
  12. self.add_all_button.clicked.connect(self.add_all)
  13. self.remove_selected_button.clicked.connect(self.remove_selected)
  14. self.remove_all_button.clicked.connect(self.remove_all)
  15. self.available_list.setSelectionMode(
  16. QtWidgets.QAbstractItemView.ExtendedSelection)
  17. self.selected_list.setSelectionMode(
  18. QtWidgets.QAbstractItemView.ExtendedSelection)
  19. def switch_selected(self, src, dst):
  20. selected = src.selectedItems()
  21. items = []
  22. for selected_item in selected:
  23. row = src.indexFromItem(selected_item).row()
  24. item = src.takeItem(row)
  25. dst.addItem(item)
  26. items.append(item)
  27. dst.sortItems()
  28. self.selectedChanged.emit()
  29. if src is self.selected_list:
  30. self.itemsRemoved.emit(items)
  31. else:
  32. self.itemsAdded.emit(items)
  33. def add_selected(self):
  34. self.switch_selected(self.available_list, self.selected_list)
  35. def remove_selected(self):
  36. self.switch_selected(self.selected_list, self.available_list)
  37. def move_all(self, src, dst):
  38. items = []
  39. while src.count() > 0:
  40. item = src.takeItem(0)
  41. dst.addItem(item)
  42. items.append(item)
  43. dst.sortItems()
  44. self.selectedChanged.emit()
  45. if src is self.selected_list:
  46. self.itemsRemoved.emit(items)
  47. else:
  48. self.itemsAdded.emit(items)
  49. def add_all(self):
  50. self.move_all(self.available_list, self.selected_list)
  51. def remove_all(self):
  52. self.move_all(self.selected_list, self.available_list)
  53. def clear(self):
  54. self.available_list.clear()
  55. self.selected_list.clear()