简体   繁体   中英

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. 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. 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. 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:

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

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

layout.insertWidget(index, newButton)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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