简体   繁体   English

PyQt 单选按钮排序列表

[英]PyQt Sort List of Radio Buttons

I am trying to dynamically create a list of radio buttons that represents the open COM ports on my computer.我正在尝试动态创建代表计算机上打开的 COM 端口的单选按钮列表。 Creating and displaying the list the first time is easy enough since I can just sort the ports to be in numerical order and then add their corresponding radio button to my vertical layout.第一次创建和显示列表很容易,因为我可以按数字顺序对端口进行排序,然后将它们对应的单选按钮添加到我的垂直布局中。

However, if the user inserts a new device which creates a new COM port, I have to find some way to add the new button in the correct place since it might not be in the right numerical order.但是,如果用户插入一个创建新 COM 端口的新设备,我必须找到一些方法将新按钮添加到正确的位置,因为它可能没有正确的数字顺序。 So far, the only way I have been able to do this is to just get rid of all the buttons and then re-add them after sorting the list since addWidget doesn't let me specify where to add the widget.到目前为止,我能够做到这一点的唯一方法是摆脱所有按钮,然后在对列表进行排序后重新添加它们,因为 addWidget 不允许我指定添加小部件的位置。 This method seems really inefficient, and I am assuming there is a simpler way, but I just have not found it yet.这种方法似乎效率很低,我假设有一个更简单的方法,但我还没有找到它。

Instead of using addWidget() , determine the index in the list of buttons to place the new one, and use QBoxLayout.insertWidget(index, widget) to insert it there:而不是使用addWidget() ,确定按钮列表中的索引以放置新的,并使用QBoxLayout.insertWidget(index, widget)将其插入:

newButton = QRadioButton(...)
newText = newButton.text()

index = 0
for button in get_buttons():
    if button.text() >= newText:
      break
    index += 1

layout.insertWidget(index, newButton)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM