16,214
社区成员
发帖
与我相关
我的任务
分享
# -*- coding:utf-8 -*-
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QCheckBox, QGridLayout, QGroupBox
class Example1(QWidget):
def __init__(self):
super( Example1, self ).__init__()
self.lString = ["aa","bb","cc","dd","ee","ff","gg","h",'i',
"aaa", "abb", "acc", "add", "aee", "aff", "agg", "ah", 'ai',
"baa", "bbb", "bcc", "bdd", "bee", "bff", "bgg", "bh", 'bi',
]
self.initUI()
def initUI(self):
iLen = len( self.lString )
lPositions = [[i,j] for i in range(int(iLen/5)+1) for j in range(5)]
pGroupBox = QGroupBox( u"游戏选择" )
pGrid = QGridLayout()
print("dir(pGrid) %s" % dir(pGrid))
pGrid.setSpacing(10)
for lPosition, sString in zip(lPositions, self.lString):
print("sGame %s" % sString)
pCheck = QCheckBox( sString )
pGrid.addWidget( pCheck, lPosition[0], lPosition[1] )
pCheck.stateChanged.connect( lambda : self.__onCheck(sString) )
pGroupBox.setLayout( pGrid )
self.setLayout( pGrid )
def __onCheck( self, value ):
print("onCheck:value %s" % value)
def __onGroup( self, value ):
print("onGroup:value %s" % value)
if __name__ == '__main__':
app = QApplication( sys.argv )
pExample1 = Example1()
pExample1.show()
sys.exit(app.exec_())
# 显示内容布局
def __strLayout( self ):
# 设置网格布局
self.pGrid = qg.QGridLayout()
# 设置间隔空间
self.pGrid.setSpacing(10)
# 将网格布局添加到当前窗口
self.layout().addLayout( self.pGrid )
iTotalNum = 20
iNumPerLine = 6
self.pBtnGroup = qg.QButtonGroup()
# 每行iNumPerLine个游戏
lPositions = [[i,j] for i in range(iTotalNum/iNumPerLine) for j in range(iNumPerLine)]
for lPosition, sName in zip( lPositions, self.lStrList ):
# 复选框
pSelectBtn = qg.QPushButton( sName )
sColor = ""
if sName in self.lCurStr:
sColor = "red"
else:
sColor = "white"
self.dMapColor_[sName] = sColor
pSelectBtn.setStyleSheet( "background-color:%s;" % sColor )
self.dMapBtn_[sName] = pSelectBtn
self.pBtnGroup.addButton( pSelectBtn )
# 添加按键到指定网格位置
self.pGrid.addWidget( pSelectBtn, lPosition[0], lPosition[1] )
self.pBtnGroup.buttonClicked.connect( self.__onSelectBtn )
最后使用 QButtonGroup /QPushButton 的方式完成,然后设置背景色来显示选中。