问题描述
import sys
from PyQt4 import QtCore, QtGui
class Class1(QtGui.QMainWindow):
def __init__(self):
super(Class1, self).__init__()
self.func()
def func(self):
r0=QtGui.QRadioButton("0",self)
r1=QtGui.QRadioButton("1",self)
ra=QtGui.QRadioButton("a",self)
rb=QtGui.QRadioButton("b",self)
r0.move(100,100)
r1.move(400,100)
ra.move(100,400)
rb.move(400,400)
number_layout=QtGui.QButtonGroup()
letter_layout=QtGui.QButtonGroup()
number_layout.addButton(r0)
number_layout.addButton(r1)
letter_layout.addButton(ra)
letter_layout.addButton(rb)
layout=QtGui.QHBoxLayout(self)
self.show()
def main():
app = QtGui.QApplication(sys.argv)
mw = Class1()
mw.show()
sys.exit(app.exec_())
if __name__=='__main__':
main()
我正在尝试将 r0,r1 和 ra,rb 分组,即当 r0 被选中时,r1 应该被取消选中,对 ra 或 rb 的状态没有影响.我怎样才能做到这一点?代码表明了我到目前为止的尝试.
I am trying to group r0,r1 and ra,rb i.e. when r0 is checked, r1 should be unchecked with no effect on states of ra or rb. How can I achieve this? The code indicates what I have tried so far.
推荐答案
QMainWindow
已经提供了一个布局,你不能简单地用你自己的替换它.要么继承一个普通的 QWidget
,要么创建一个新的小部件并添加布局和按钮.
A QMainWindow
provides a layout already, you can't simply replace that with your own. Either inherit from a plain QWidget
, or create a new widget and add the layout and buttons to that.
你的命名也很混乱,QButtonGroup
不是布局.它实际上并不提供任何可见的 UI.如果您需要一个对按钮进行分组的 UI 元素,您应该查看 QGroupBox
.
Your naming is confusing too, QButtonGroup
isn't a layout. It doesn't actually provide any visible UI. If you need a UI element that groups buttons, you should look at QGroupBox
instead.
以下是您上述内容的简单变体:
Here's a simple variation on what you have above:
def func(self):
layout=QtGui.QHBoxLayout() # layout for the central widget
widget=QtGui.QWidget(self) # central widget
widget.setLayout(layout)
number_group=QtGui.QButtonGroup(widget) # Number group
r0=QtGui.QRadioButton("0")
number_group.addButton(r0)
r1=QtGui.QRadioButton("1")
number_group.addButton(r1)
layout.addWidget(r0)
layout.addWidget(r1)
letter_group=QtGui.QButtonGroup(widget) # Letter group
ra=QtGui.QRadioButton("a")
letter_group.addButton(ra)
rb=QtGui.QRadioButton("b")
letter_group.addButton(rb)
layout.addWidget(ra)
layout.addWidget(rb)
# assign the widget to the main window
self.setCentralWidget(widget)
self.show()
这篇关于PyQt 中的单选按钮分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!