添加链接
link之家
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
相关文章推荐
温暖的便当  ·  React ...·  5 月前    · 
另类的勺子  ·  mysql ...·  9 月前    · 
霸气的酸菜鱼  ·  RxJava 创建操作符 ...·  1 年前    · 
self.comboBox = QComboBox(self) self.comboBox.resize( 100 , 30 ) self.comboBox.move( 100 , 100 ) self.test() def test ( self ): ############################添加条目项############################### self.comboBox.addItem( "xx1" ) self.comboBox.addItem( "xx2" ) self.comboBox.addItem(QIcon( "icon/view.png" ), "xx3" ) self.comboBox.addItems([ "xx1" , "xx2" , "xx3" ]) ############################添加条目项############################### if __name__ == '__main__' : app =QApplication(sys.argv) window = Window() window.show() sys.exit(app.exec_()) 添加条目项

插入 (指定位置插入)

设置 (替换)

from PyQt5.Qt import * #刚开始学习可以这样一下导入 import sys class Window ( QWidget ): def __init__ ( self ): super ().__init__() self.setWindowTitle( "QComboBox的学习" ) self.resize( 400 , 400 ) self.set_ui() def set_ui ( self ): self.comboBox = QComboBox(self) self.comboBox.resize( 100 , 30 ) self.comboBox.move( 100 , 100 ) self.test() def test ( self ): ############################插入条目项############################### self.comboBox.addItems([ "xx1" , "xx2" , "xx3" ]) self.comboBox.insertItem( 1 ,QIcon( "icon/view.png" ), "xxx4" ) # self.comboBox.insertItems() ############################设置条目############################### self.comboBox.setItemIcon( 2 ,QIcon( "icon/xiaoxio.png" )) self.comboBox.setItemText( 3 , "fsadjffajs" ) ############################删除条目项############################### # self.comboBox.removeItem(3) ############################删除条目项############################### self.comboBox = QComboBox(self) self.comboBox.resize( 100 , 30 ) self.comboBox.move( 100 , 100 ) self.test() def test ( self ): self.comboBox.addItems([ "xx1" , "xx2" , "xx3" ]) ############################设置分割线############################### self.comboBox.insertSeparator( 2 ) # 表示在2的前面加 ############################设置 当前选项############################### self.comboBox.setCurrentIndex( 3 ) ############################设置 编辑文本############################### self.comboBox.setEditable( True ) # 需要这个开启下面两个才会生效 # self.comboBox.setEditText("zzzzz") #设置文本 # self.comboBox.setCurrentText("11111") # 同上 self.comboBox = QComboBox(self) self.comboBox.resize( 200 , 30 ) self.comboBox.move( 100 , 100 ) self.test() def test ( self ): """表示把下拉框设置成树型""" qtv=QTreeView() self.comboBox.setView(qtv) model=qtv.model() # 表示添加树的根 # model = QStandardItemModel() # 下面这种也可以 # print(QAbstractItemModel.__subclasses__()) self.comboBox.setModel(model) # ---------------------设置选项-------------------------------- # 1- 添加所有的选项 item1 = QStandardItem( "item1" ) item2 = QStandardItem( "item2" ) item22 = QStandardItem( "item22" ) item23 = QStandardItem(QIcon( "icon/view.png" ), "item23" ) # 2- 把选项放在树上 model.appendRow(item1) model.appendRow(item2) item2.appendRow(item22) item2.appendRow(item23) # ---------------------设置选项-------------------------------- self.comboBox = QComboBox(self) self.comboBox.resize( 200 , 30 ) self.comboBox.move( 100 , 100 ) self.test() def test ( self ): """表示把下拉框设置成多选形式""" qw=QListWidget() self.comboBox.setView(qw) self.comboBox.setModel(qw.model()) # self.comboBox.setLineEdit(QLineEdit()) # 决定有没有第一行输入框 # ---------------------设置选项-------------------------------- """1设置第一个选项""" qItem = QListWidgetItem(qw) qb1 = QCheckBox() qb1.setText( "试试" ) qw.setItemWidget(qItem, qb1) """2设置第二个选项""" qItem2 = QListWidgetItem(qw) qb2 = QCheckBox() qb2.setText( "再试试" ) qw.setItemWidget(qItem2, qb2) # ---------------------设置选项--------------------------------
  • comboBox.count() 获取选项数
  • comboBox.currentIndex() 获取当前选中项索引
  • comboBox.currentText() 获取当前选中项内容
  • comboBox.itemIcon(int index) --> QIcon 下面的例子是获取到,然后放到按钮上
  • comboBox.itemText(4) - 获取指定索引选项
  • comboBox.itemData(4) 获取指定索引选项
  • from PyQt5.Qt import * #刚开始学习可以这样一下导入
    import sys
    class Window(QWidget):
        def __init__(self):
            super().__init__()
            self.setWindowTitle("QComboBox的学习")
            self.resize(400,400)
            self.set_ui()
        def set_ui(self):
            self.comboBox = QComboBox(self)
            self.comboBox.resize(100,30)
            self.comboBox.move(100,100)
            self.test()
            btn = QPushButton(self)
            btn.setText("按钮")
            btn.move(0,300)
            # btn.clicked.connect(lambda :print(self.comboBox.count()))
            # btn.clicked.connect(lambda :print(self.comboBox.currentIndex()))
            # btn.clicked.connect(lambda :print(self.comboBox.currentText()))
            btn.clicked.connect(lambda :print(self.comboBox.itemText(4)))       # 获取指定索引  显示文本
            btn.clicked.connect(lambda :print(self.comboBox.itemData(4)))       # 获取指定索引  data
            # 获取Qicon,然后放到按钮身上
            # btn.clicked.connect(lambda :btn.setIcon(self.comboBox.itemIcon(self.comboBox.currentIndex())))
            #小技巧1.---- self.comboBox.count()-1 表示最后一个选项索引
            btn.clicked.connect(lambda _,idx = self.comboBox.count()-1:print(self.comboBox.itemIcon(idx)))
                     #小技巧1 的解析
            last_one=self.comboBox.count()-1
            btn.clicked.connect(lambda :print(self.comboBox.itemIcon(last_one)))
        def test(self):
            self.comboBox.addItems(["xx1","xx2","xx3"])
            self.comboBox.insertItem(1,QIcon("icon/view.png"),"xxx4")
            self.comboBox.addItem(QIcon("icon/xiaoxio.png"),"fajsd",{"name":"tom"})
    if __name__ == '__main__':
        app =QApplication(sys.argv)
        window = Window()
        window.show()
        sys.exit(app.exec_())
    

    六、选项限制

  • .setMaxCount(3)
  • .maxCount()
  • 选项可见范围个数

  • .setMaxVisibleItems(10)
  • .maxVisibleItems()
  • from PyQt5.Qt import * #刚开始学习可以这样一下导入
    import sys
    class Window(QWidget):
        def __init__(self):
            super().__init__()
            self.setWindowTitle("QComboBox的学习")
            self.resize(400,400)
            self.set_ui()
        def set_ui(self):
            self.comboBox = QComboBox(self)
            self.comboBox.resize(100,30)
            self.comboBox.move(100,100)
            self.test()
            btn = QPushButton(self)
            btn.setText("按钮")
            btn.move(0,300)
            btn.clicked.connect(lambda :self.comboBox.addItem("xxx"))
        def test(self):
            self.comboBox.addItems(["xx1","xx2","xx3"])
            self.comboBox.insertItem(1,QIcon("icon/view.png"),"xxx4")
            ############################数据的限制###############################
            self.comboBox.setMaxCount(3)
            print(self.comboBox.maxCount())
            self.comboBox.setMaxVisibleItems(10)  #一屏可以显示的个数
            print(self.comboBox.maxVisibleItems())
            ############################数据的限制###############################
    if __name__ == '__main__':
        app =QApplication(sys.argv)
        window = Window()
        window.show()
        sys.exit(app.exec_())
    

    七、其他操作

    设置为可编辑

    允许编辑内容
    

    设置为可重复

    设置图标大小

    from PyQt5.Qt import * #刚开始学习可以这样一下导入 import sys class Window(QWidget): def __init__(self): super().__init__() self.setWindowTitle("QComboBox的学习") self.resize(400,400) self.set_ui() def set_ui(self): self.comboBox = QComboBox(self) self.comboBox.resize(100,30) self.comboBox.move(100,100) self.test() def test(self): self.comboBox.addItem(QIcon("icon/view.png"),"xx3") self.comboBox.addItems(["xx1","xx2","xx3"]) # 可编辑 self.comboBox.setEditable(True) print("是否可编辑",self.comboBox.isEditable()) # 可重复 (不知道什么用) self.comboBox.setDuplicatesEnabled(True) print("是否可编辑",self.comboBox.duplicatesEnabled()) # 没有框架-默认为True # self.comboBox.setFrame(False) print(self.comboBox.hasFrame()) # 设置图标大小 self.comboBox.setIconSize(QSize(60, 60)) if __name__ == '__main__': app =QApplication(sys.argv) window = Window() window.show() sys.exit(app.exec_())

    弹开下拉框

    它的用途是,自己自定义一个控制,然后通过点击自定义的也能弹出下拉框
    comboBox.showPopup()

    from PyQt5.Qt import *  # 刚开始学习可以这样一下导入
    import sys
    class Window(QWidget):
        def __init__(self):
            super().__init__()
            self.setWindowTitle("QComboBox的学习")
            self.resize(400, 400)
            self.set_ui()
        def set_ui(self):
            self.comboBox = QComboBox(self)
            self.comboBox.resize(100, 30)
            self.comboBox.move(100, 100)
            self.test()
            btn = QPushButton(self)
            btn.setText("按钮")
            btn.move(0, 300)
            btn.clicked.connect(self.slot_test)
        def slot_test(self):
            ############################设置弹出列表###############################
            self.comboBox.showPopup()
            # 它的用途是,自己自定义一个控制,然后通过点击自定义的也能弹出下拉框
        def test(self):
            self.comboBox.addItems(["xx1", "xx2", "xx3"])
            self.comboBox.insertItem(1, QIcon("icon/view.png"), "xxx4")
            self.comboBox = QComboBox(self)
            self.comboBox.resize(100, 30)
            self.comboBox.move(100, 100)
            self.test()
            btn = QPushButton(self)
            btn.setText("清空所有项目")
            btn.move(0, 300)
            btn.clicked.connect(self.slot_test)
            btn1 = QPushButton(self)
            btn1.setText("清空编辑的文本")
            btn1.move(100, 300)
            btn1.clicked.connect(self.slot_test2)
        def slot_test(self):
            self.comboBox.clear()  #清空所有项目
        def slot_test2(self):
            self.comboBox.clearEditText()  #清空编辑的文本
        def test(self):
            self.comboBox.addItems(["xx1", "xx2", "xx3"])
            self.comboBox.insertItem(1, QIcon("icon/view.png"), "xxx4")
            ############################尺寸调整策略###############################
            self.comboBox.setSizeAdjustPolicy(QComboBox.AdjustToContents)  # 参照最长的长度
            # self.comboBox.setSizeAdjustPolicy(QComboBox.AdjustToContentsOnFirstShow)  # 根据第一次显示 来适应
            # self.comboBox.setSizeAdjustPolicy(QComboBox.AdjustToMinimumContentsLength)
            # self.comboBox.setSizeAdjustPolicy(QComboBox.AdjustToMinimumContentsLengthWithIcon)
            self.comboBox.setEditable(True)
    if __name__ == '__main__':
        app = QApplication(sys.argv)
        window = Window()
        window.show()
        sys.exit(app.exec_())
    

    输入时支持搜索(完成器)

    from PyQt5.Qt import * #刚开始学习可以这样一下导入
    import sys
    class Window(QWidget):
        def __init__(self):
            super().__init__()
            self.setWindowTitle("QComboBox的学习")
            self.resize(400,400)
            self.set_ui()
        def set_ui(self):
            self.comboBox = QComboBox(self)
            self.comboBox.resize(100,30)
            self.comboBox.move(100,100)
            self.test()
            btn = QPushButton(self)
            btn.setText("按钮")
            btn.move(0,300)
            btn.clicked.connect(self.slot_test)
        def slot_test(self):
        def test(self):
            self.comboBox.addItems(["xx1","xx2","bb3","cc4"])
            self.comboBox.setEditable(True)
            self.comboBox.setCompleter(QCompleter(["xx1","xx2","bb3"]))
            #注意:完成器中的内容一般要和 下拉框中的条目一致  ,这样可以达到快速的匹配
            self.comboBox = QComboBox(self)
            self.comboBox.resize(100,30)
            self.comboBox.move(100,100)
            self.test()
            btn = QPushButton(self)
            btn.setText("按钮")
            btn.move(0,300)
            btn.clicked.connect(self.slot_test)
        def slot_test(self):
        def test(self):
            self.comboBox.addItems(["xx1","xx2","xx3"])
            self.comboBox.setEditable(True)
            ############################信号###############################
            """被选中信号(手动选时)"""
            # 1.被选中信号:activated       默认释放的参数:为被选中的索引值
            self.comboBox.activated.connect(lambda val:print("选项被选中",val))      # 信号信号的参数 为  被选中的索引值
            # self.comboBox.activated.connect(lambda val:print("条目被激活",self.comboBox.itemText(val)))  # 拓展(这样就和下面一样了)
            # 2.被选中信号2:activated[str]         释放的参数:为被选中的 显示文本
            self.comboBox.activated[str].connect(lambda val:print("选项被选中",val))
            """选中选项发生改变(手动去改变,或代码改变时)"""
            # 以上两个信号仅仅是和用户交互的时候发射的信号,如果此时用代码改变,它不会发射信号
            # 如果也想检测到用代码改变的事件,用下面:
            self.comboBox.currentIndexChanged.connect(lambda val:print(f"当前索引发生改变变成{val}"))
            self.comboBox.currentIndexChanged[str].connect(lambda val:print(f"当前选项值发生改变变成{val}"))
            """当前的文本发生改变时(编辑)"""
            self.comboBox.currentTextChanged.connect(lambda val:print("当前文本发生改变",val)) #编辑的时候改变
            self.comboBox.editTextChanged.connect(lambda val:print("当前编辑文本发生改变",val))  # 和上面差不多
            """高亮发生改变时(悬停时,就改变)"""
            self.comboBox.highlighted.connect(lambda val:print("高亮发生改变",val))
    if __name__ == '__main__':
        app =QApplication(sys.argv)
        window = Window()
        window.show()
        sys.exit(app.exec_())
    

    九、两级下拉选项案例

    '版本1'
    from PyQt5.Qt import * #刚开始学习可以这样一下导入
    import sys
    class Window(QWidget):
        def __init__(self):
            super().__init__()
            self.setWindowTitle("QComboBox 的案例")
            self.resize(400,400)
            self.city_dict= {
                "河南":{
                    "郑州":"001",
                    "开封":"002",
                    "洛阳":"003",
                    "南阳":"004",
                "江西":{
                    "南昌":"005",
                    "福州":"006",
                    "乾州":"007",
                    "上海":"008",
                "广东":{
                    "广州":"009",
                    "深圳":"010",
                    "湛江":"011",
                    "佛山":"012",
            self.set_ui()
        def set_ui(self):
            #1创建两个下拉框控件
            pro = QComboBox(self)
            city = QComboBox(self)
            self.city = city
            pro.move(100,100)
            city.move(200,100)
            # 2,展示数据到第一个下拉框
            pro.addItems(self.city_dict.keys())
            # 3,触发一下函数,展示数据到第二个下拉框
            self.pro_currentIndexChanged_slot(pro.currentText())
            #3 监听第一个下拉列表里面的当前值  发生改变的信号---------->去改变第二个下拉框
            pro.currentIndexChanged[str].connect(self.pro_currentIndexChanged_slot)
            #5 监听第二个列表中发生改变的信号------------------>去打印当前选中的 值
            city.currentIndexChanged[int].connect(self.city_currentIndexChanged_slot)
        def pro_currentIndexChanged_slot(self,pro_name):
            # print(pro_name)
            #4,根据第一个的名称来获取对应城市列表
            self.city.clear()
            cities = self.city_dict[pro_name]
            # self.city.addItems(cities)
            for key,val in cities.items():  #这种有自己的Userdata  它可用索引获取data
                # print(key,val)
                self.city.addItem(key,val)
        def city_currentIndexChanged_slot(self,idx):
            # print("第二个列表发生改变的时候",idx)
            userData = self.city.itemData(idx)
            if userData != None:
                print(userData)
    if __name__ == '__main__':
        app =QApplication(sys.argv)
        window = Window()
        window.show()
        sys.exit(app.exec_())
    

    版本1以上代码存在点问题

    from PyQt5.Qt import * #刚开始学习可以这样一下导入
    import sys
    class Window(QWidget):
        def __init__(self):
            super().__init__()
            self.setWindowTitle("QComboBox 的案例")
            self.resize(400,400)
            self.city_dict = {
                "河南": {
                    "郑州": "001",
                    "开封": "002",
                    "洛阳": "003",
                    "南阳": "004",
                "江西": {
                    "南昌": "005",
                    "福州": "006",
                    "乾州": "007",
                    "上海": "008",
                "广东": {
                    "广州": "009",
                    "深圳": "010",
                    "湛江": "011",
                    "佛山": "012",
            self.set_ui()
        def set_ui(self):
            #1创建两个下拉框控件
            pro = QComboBox(self)
            city = QComboBox(self)
            self.city = city
            pro.move(100,100)
            city.move(200,100)
            #3 监听第一个下拉列表里面的当前值  发生改变的信号
            pro.currentIndexChanged[str].connect(self.pro_currentIndexChanged_slot)
            #5 监听第二个列表中发生改变的信号
            city.currentIndexChanged[int].connect(self.city_currentIndexChanged_slot)
            # 2,展示数据到第一个下拉框
                         #一定要注意要先连接信号,然后再去添加数据,不然第一个就无法触发
            pro.addItems(self.city_dict.keys())
        def pro_currentIndexChanged_slot(self,pro_name):
            # print(pro_name)
            #4,根据第一个的名称来获取对应城市列表
            self.city.blockSignals(True)
            self.city.clear()  # 第二种解决None 产生的方法,当clear 时 ,将信号临时阻断
            self.city.blockSignals(False)
            cities = self.city_dict[pro_name]
            # self.city.addItems(cities)
            for key,val in cities.items():  #这种有自己的Userdata  它可用索引获取data
                self.city.addItem(key,val)
        def city_currentIndexChanged_slot(self,idx):
            # print("第二个列表发生改变的时候",idx)
            userData = self.city.itemData(idx)
            # if userData != None:  #第一种解决None 的方法
            #     print(userData)
            print(userData)
    if __name__ == '__main__':
        app =QApplication(sys.argv)
        window = Window()
        window.show()
        sys.exit(app.exec_())
    

    十、QComboBox相关子类

    from PyQt5.Qt import * #刚开始学习可以这样一下导入
    import sys
    class Window(QWidget):
        def __init__(self):
            super().__init__()
            self.setWindowTitle("QFontComboBox 的学习")
            self.resize(400,400)
            self.set_ui()
        def set_ui(self):
            label = QLabel(self)
            label.setText("我爱中国")
            label.move(100,100)
            fontComboBox = QFontComboBox(self)
            #一个重要的信号
            # fontComboBox.currentFontChanged.connect(lambda font:print(font))
            fontComboBox.currentFontChanged.connect(lambda font:label.setFont(font))
            fontComboBox.setEditable(False)
    if __name__ == '__main__':
        app =QApplication(sys.argv)
        window = Window()
        window.show()
        sys.exit(app.exec_())
    

    十一、扩展封装多选组件

    from PyQt5.QtWidgets import QComboBox, QLineEdit, QListWidget, QCheckBox, QListWidgetItem, QApplication
    from PyQt5.QtCore import pyqtSignal
    class ComboCheckBox(QComboBox):
        1.将show函数改成show_items
        2.增加changeitemlist函数
        3.增加信号signa
        signa = pyqtSignal(list)
        def __init__(self):
            super(ComboCheckBox, self).__init__()
            self.items = ['全部']
            self.row_num = len(self.items)
            self.Selectedrow_num = 0
            self.qCheckBox = []
            self.qLineEdit = QLineEdit()
            self.qLineEdit.setReadOnly(True)
            self.qListWidget = QListWidget()
            self.outputlist = []
            self.selected_id = []
            self.addQCheckBox(0)
            self.qCheckBox[0].stateChanged.connect(self.select_all)
            for i in range(1, self.row_num):
                self.addQCheckBox(i)
                self.qCheckBox[i].stateChanged.connect(self.show_selected)
            self.setModel(self.qListWidget.model())
            self.setView(self.qListWidget)
            self.setLineEdit(self.qLineEdit)
            # 避免滑条的出现引起滑条偷吃标签的问题
            self.setMaxVisibleItems(100)
        def addQCheckBox(self, i):
            self.qCheckBox.append(QCheckBox())
            qItem = QListWidgetItem(self.qListWidget)
            self.qCheckBox[i].setText(self.items[i])
            self.qListWidget.setItemWidget(qItem, self.qCheckBox[i])
        def Selectlist(self):
            self.outputlist = []
            self.selected_id = []
            for i in range(1, self.row_num):
                if self.qCheckBox[i].isChecked():
                    self.selected_id.append(i)
                    self.outputlist.append(self.qCheckBox[i].text())
            self.Selectedrow_num = len(self.outputlist)
            return self.outputlist
        def show_selected(self):
            show_items = ''
            self.Selectlist()
            self.signa.emit(self.outputlist)
            # print(self.outputlist)
            self.qLineEdit.setReadOnly(False)
            self.qLineEdit.clear()
            for item in self.outputlist:
                show_items += item + ';'
            if self.Selectedrow_num == 0:
                self.qCheckBox[0].setCheckState(0)
            elif self.Selectedrow_num == self.row_num - 1:
                self.qCheckBox[0].setCheckState(2)
            else:
                self.qCheckBox[0].setCheckState(1)
            self.qLineEdit.setText(show_items[:-1])
            self.qLineEdit.setReadOnly(True)
        def select_all(self, status):
            if status == 2:
                for i in range(1, self.row_num):
                    self.qCheckBox[i].setChecked(True)
            elif status == 1:
                if self.Selectedrow_num == 0:
                    self.qCheckBox[0].setCheckState(2)
            elif status == 0:
                self.clear()
        def clear(self):
            for i in range(self.row_num):
                self.qCheckBox[i].setChecked(False)
        def change_item_list(self, itemlist):
            self.items = itemlist
            self.items.insert(0, '全部')
            self.row_num = len(self.items)
            self.Selectedrow_num = 0
            self.qCheckBox = []
            self.qLineEdit = QLineEdit()
            self.qLineEdit.setReadOnly(True)
            self.qListWidget = QListWidget()
            self.addQCheckBox(0)
            self.qCheckBox[0].stateChanged.connect(self.select_all)
            for i in range(1, self.row_num):
                self.addQCheckBox(i)
                self.qCheckBox[i].stateChanged.connect(self.show_selected)
            self.setModel(self.qListWidget.model())
            self.setView(self.qListWidget)
            self.setLineEdit(self.qLineEdit)
    if __name__ == "__main__":
        import sys, time
        app = QApplication(sys.argv)
        mainWindow = ComboCheckBox()
            # def solt11(x):
        #     print(x)
        # mainWindow.signa.connect(solt11)
        mainWindow.show()
        mainWindow.change_item_list(['装置ID1', '传感器ID1', "采样时间1", '装置电源电压1', "信号强度1",'装置ID2', '传感器ID2', "采样时间2", '装置电源电压2', "信号强度3",'装置ID3', '传感器ID3', "采样时间3", '装置电源电压3', "信号强度4"])
        sys.exit(app.exec_())
        成都_陶木木
           
    粉丝