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_())

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

相关推荐

  1. Qt 遍历Combbox内容并进行判断

    2024-05-13 19:24:06       23 阅读
  2. Android 14.0 SystemUI状态栏增加响铃功能

    2024-05-13 19:24:06       32 阅读
  3. Vuetify3:v-data-table增加筛选

    2024-05-13 19:24:06       18 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-05-13 19:24:06       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-05-13 19:24:06       101 阅读
  3. 在Django里面运行非项目文件

    2024-05-13 19:24:06       82 阅读
  4. Python语言-面向对象

    2024-05-13 19:24:06       91 阅读

热门阅读

  1. KAN网络

    KAN网络

    2024-05-13 19:24:06      34 阅读
  2. 微调大模型学习记录

    2024-05-13 19:24:06       36 阅读
  3. MFC--CCreateContext结构体

    2024-05-13 19:24:06       34 阅读
  4. 三种基本排序-冒泡,选择,二分

    2024-05-13 19:24:06       35 阅读
  5. MySQL中所有数据类型

    2024-05-13 19:24:06       26 阅读
  6. MongoDB聚合运算符:$topN

    2024-05-13 19:24:06       32 阅读
  7. stylus详解与引入

    2024-05-13 19:24:06       37 阅读
  8. 深度学习学习日记(5.6)

    2024-05-13 19:24:06       29 阅读
  9. 初级银行从业资格证知识点(十)

    2024-05-13 19:24:06       32 阅读
  10. 升级WSL Ubuntu内核从5.10到5.15

    2024-05-13 19:24:06       35 阅读
  11. Flink面试整理-Flink的配置管理包含哪些?

    2024-05-13 19:24:06       35 阅读
  12. Python Pandas 数据分析快速入门

    2024-05-13 19:24:06       29 阅读
  13. el-tree

    2024-05-13 19:24:06       78 阅读
  14. QT 文字转语言插件

    2024-05-13 19:24:06       34 阅读