PyQt--创建下拉可增加项目的Combobox

设置下拉框,且根据需要增加下拉框的元素,并同步保存到接送文件中便于下次调用。

import os
import sys
import glob
import json
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.Qt import *
from PyQt5.QtCore import *

class TimeSelection(QComboBox):
    def __init__(self, parent=None):
        """
        Initialize the TimeSelection combobox.

        Args:
            parent: The parent widget.
        """
        super().__init__(parent)

        # Set font size and display effect
        self.setStyleSheet("QComboBox { padding: 5px; }")

        # Set the dropdown list view
        self.listview = QListWidget(parent)
        self.listview.setStyleSheet("QListWidget { font-size: 22px; }")
        self.viewmodel = self.listview.model()
        self.setView(self.listview)
        self.setModel(self.viewmodel)
        self.view().setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)

        # Read data
        self.data_path = "data/control_time.json"
        try:
            with open(self.data_path, 'r') as file:
                self.data = json.load(file)
        except FileNotFoundError:
            self.data = {}

        # Add existing options
        for item, info in self.data.items():
            self.addItem(f'{item} {info["unit"]}')

        # Add edit line and button
        self.add_editline_button()

    def add_editline_button(self):
        """
        Add an edit line and button to the TimeSelection combobox.
        """
        item_widget = QWidget()
        layout = QHBoxLayout(item_widget)
        self.time_input_field = QLineEdit()
        self.time_input_field.setPlaceholderText('Enter A Time')
        # Set font size and display effect for the edit line
        self.listview.setStyleSheet("QLineEdit { font-size: 22px; }")
        
        layout.addWidget(self.time_input_field)

        # Add button
        self.add_time_select_btn = QPushButton()
        add_icon = QIcon('data/image/add.png')
        self.add_time_select_btn.setIcon(add_icon)
        self.add_time_select_btn.setToolTip('Add Time selection')
        self.add_time_select_btn.setIconSize(QSize(20, 20))

        # Set button style
        self.add_time_select_btn.setStyleSheet("QPushButton { border: none; }")

        # Connect button click event
        self.add_time_select_btn.clicked.connect(self.add_time)
        layout.addWidget(self.add_time_select_btn)
        layout.setContentsMargins(0, 0, 0, 0)

        # Add to the list
        item_list = self.listview
        item_wrap = QListWidgetItem(item_list)
        item_list.setItemWidget(item_wrap, item_widget)
    
    def add_time(self):
        """
        Add a new time selection to the combobox.
        """
        new_time = self.time_input_field.text()
        
        try:
            # Try to convert input to float
            new_time_value = float(new_time)
            
            # If conversion succeeds, proceed with the operation
            self.insertItem(self.count() - 1, f'{new_time_value} s')
            self.data[str(new_time_value)] = {'name': f'{new_time_value}', 'unit': 's'}
            
            # Save data to file
            with open(self.data_path, 'w') as file:
                json.dump(self.data, file, indent=4)
            
            # Clear the input field
            self.time_input_field.clear()
        
        except ValueError:
            # If the conversion fails, a error message will be prompted.
            QMessageBox.critical(self, "Error", "Please Input an Integer or Float")
            

        

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = TimeSelection()
    window.setGeometry(500, 300, 100, 50)
    window.show()
    sys.exit(app.exec_())

效果如下:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值