我的程序基于SQL数据即时生成表单。我在它们旁边制作了两个单选按钮和一个QLineEdit条目。选中右侧的单选按钮后,将正确启用QLineEdit。问题来自单选按钮之间的链接,并导致它们之间的排他性操作。程序启动时,它们如下所示:
然后,当我单击第一个“否”时,它将更改我的期望并启用QLineEdit。
现在,我也要为“序列号:RC1”单击“否”。这是行为开始出错的地方。 单击“否”按钮,然后取消选择上面的所有行。
如果我尝试再次单击第一行的“否”,则取消选择第二行的“是”。
最后,我可以单击“选定”单选按钮,然后取消选择所有内容,直到剩下一个活动的单选按钮。在这一点上,我不能只选择一个按钮。单击取消选择的按钮将激活它,然后取消选择先前处于活动状态的按钮。
我通过将单选按钮放入QButtonGroups的辅助函数即时生成按钮。我认为这足以阻止这种行为,但是我错了。 我想要的是每行上的单选按钮不响应其他行上其他单选按钮的操作。
# !/user/bin/env python
import os
import sys
from PyQt5 import uic
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
class Radio(QDialog):
def __init__(self, app):
super(Radio, self).__init__()
self.bundle_dir = os.path.dirname(__file__)
gui_path = os.path.join(self.bundle_dir, 'ui', 'radio_bt_test.ui')
self.ui = uic.loadUi(gui_path, self)
self.num_of_row = 4
self.formLayout = self.findChild(QFormLayout, "formLayout")
self.radio_bt_lineEdit_connections = dict() # to help link the radio buttons and lineEdit
self.add_rows()
self.show()
def add_rows(self):
"""
Adds pairs of radio buttons with a lineEdit to each row of the form layout
:return:
"""
for i in range(self.num_of_row):
lbl = QLabel("Label#" + str(i))
hbox = QHBoxLayout()
buttons = self.new_radio_pair()
entry = self.new_entry("Value if No")
entry.setEnabled(False)
self.radio_bt_lineEdit_connections[buttons[-1]] = entry
# adding connection to dictionary for later event handling
buttons[-1].toggled.connect(self.radio_bt_changed)
for button in buttons:
hbox.addWidget(button)
hbox.addWidget(entry)
self.formLayout.addRow(lbl, hbox)
def new_radio_pair(self, texts=('Yes', 'No')) -> list:
"""
Makes a pair of radio buttons in a button group for creating data entries in "Part" grouping on the fly
:param texts: The texts that will go on the two buttons. The more texts that are added to make more radio buttons
:return: A list with QRadioButtons that are all part of the same QButtonGroup
"""
group = QButtonGroup()
buttons = []
for text in texts:
bt = QRadioButton(text)
bt.setFont(QFont('Roboto', 11))
if text == texts[0]:
bt.setChecked(True)
group.addButton(bt)
buttons.append(bt)
return buttons
def radio_bt_changed(self) -> None:
"""
Helps the anonymous radio buttons link to the anonymous QLineEdits that are made for data fields
:return: None
"""
sender = self.sender()
assert isinstance(sender, QRadioButton)
lineEdit = self.radio_bt_lineEdit_connections[sender]
assert isinstance(lineEdit, QLineEdit)
if sender.isChecked():
lineEdit.setEnabled(True)
else:
lineEdit.setEnabled(False)
lineEdit.clear()
def new_entry(self, placeholder_text: str = "") -> QLineEdit:
"""
Makes a new QLineEdit object for creating data entries in "Part" grouping on the fly
:return: A new QLineEdit with appropriate font and size policy
"""
entry = QLineEdit()
entry.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
entry.setFont(QFont('Roboto', 11))
entry.setStyleSheet("background-color: rgb(239, 241, 243);")
# with style sheets, past anything in here between the css tags
entry.setMaxLength(15)
entry.setPlaceholderText(placeholder_text)
return entry
def main():
app = QApplication(sys.argv)
radio = Radio(app)
sys.exit(app.exec())
main()
可能是因为我声明了QButtonGroup然后忘记了它们吗?是因为我没有分配变量,还是因为我遗漏了另一个问题,垃圾收集器会来清除它们吗?
ui是在QtDesigner上设计的,只是一个带有表单布局的对话框。
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>Dialog</class>
<widget class="QDialog" name="Dialog">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>491</width>
<height>382</height>
</rect>
</property>
<property name="windowTitle">
<string>Dialog</string>
</property>
<property name="styleSheet">
<string notr="true">background-color: rgb(219, 221, 223);</string>
</property>
<widget class="QWidget" name="formLayoutWidget">
<property name="geometry">
<rect>
<x>80</x>
<y>40</y>
<width>301</width>
<height>291</height>
</rect>
</property>
<layout class="QFormLayout" name="formLayout"/>
</widget>
</widget>
<resources/>
<connections/>
</ui>
答案 0 :(得分:1)
用于使行按钮互斥的对象是“组”,但这是一个局部变量,当new_radio_pair方法完成执行时,该局部变量将被破坏,从而导致其行为不像以前想象的那样。
解决方案是延长生命周期,为此有多种选择,例如使其成为类的属性,将其添加到具有较长生命周期的容器或类中,或者对于QObjects,则通过另一个QObject作为父对象(如self
)具有更长的生命周期,这是这种情况下的最佳解决方案:
group = QButtonGroup(self)