PyQt 创建多选下拉框 选中可在选框中显示内容 点击按钮获取选中值 并弹窗显示选中值
时间: 2024-05-03 14:23:00 浏览: 18
下面是一个简单的示例代码,可以创建一个多选下拉框,选中的内容将显示在选框中,点击按钮可以获取选中的值并弹窗显示。
```python
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QComboBox, QLabel, QPushButton, QMessageBox
class MultiSelectComboBox(QWidget):
def __init__(self, parent=None):
super().__init__(parent)
self.initUI()
def initUI(self):
self.layout = QVBoxLayout()
self.combobox = QComboBox(self)
self.combobox.setEditable(True)
self.combobox.setInsertPolicy(QComboBox.NoInsert)
self.combobox.view().pressed.connect(self.handle_item_pressed)
self.label = QLabel(self)
self.label.setText("Selected items:")
self.layout.addWidget(self.combobox)
self.layout.addWidget(self.label)
self.setLayout(self.layout)
def handle_item_pressed(self, index):
item = self.combobox.itemText(index)
if item:
if index.row() == -1:
self.combobox.addItem(item)
else:
self.combobox.removeItem(index.row())
def getSelectedItems(self):
selected_items = []
for index in range(self.combobox.count()):
item = self.combobox.itemText(index)
selected_items.append(item)
return selected_items
class MainWindow(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.layout = QVBoxLayout()
self.combobox = MultiSelectComboBox(self)
self.layout.addWidget(self.combobox)
self.button = QPushButton("Get Selected Items", self)
self.button.clicked.connect(self.show_selected_items)
self.layout.addWidget(self.button)
self.setLayout(self.layout)
def show_selected_items(self):
selected_items = self.combobox.getSelectedItems()
if selected_items:
message = "Selected Items:\n\n" + "\n".join(selected_items)
else:
message = "No Items Selected!"
QMessageBox.information(self, "Selected Items", message)
if __name__ == "__main__":
import sys
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
```
在上面的代码中,我们定义了一个名为 `MultiSelectComboBox` 的自定义小部件,它继承自 `QWidget`。该小部件包含一个 `QComboBox` 和一个 `QLabel`,用于显示选中的项目。我们还定义了一个名为 `handle_item_pressed` 的方法,它将处理通过单击下拉框中的项来选择或取消选择该项的操作。我们还定义了一个名为 `getSelectedItems` 的方法,它将返回选中的项目。
在 `MainWindow` 类中,我们创建了一个 `MultiSelectComboBox` 实例,并将其添加到一个垂直布局中。我们还创建了一个 `QPushButton`,用于获取选中的项目,并将其添加到相同的布局中。当用户单击该按钮时,我们将显示一个包含选中项目的消息框。