python3 pyqt5在一个过程中创建多个QCHECKBOX小部件

发布于 2025-01-25 06:49:46 字数 5391 浏览 0 评论 0原文

需要在Qgridlayout中添加多个QCHECKBOX项​​目的指导,以便在处理从数据库返回的数据进行处理。

我创建了一个带有标识产品类别的选项卡的窗口。每个选项卡都包含产品的网格布局。每种产品都有一个复选框,可以在其中选择进一步处理。

我的窗户看起来像这样:

“产品窗口的图像”

我的创建窗口的代码是(我已经斜体化了我遇到问题的区域):

def prodTab(self):
self.resize(950,400)
## Products tab
layoutv = QVBoxLayout() ## Main area layout
layoutg = QGridLayout() ## Layout for the top button area

## Main function buttons
btncatadd = QPushButton("New Category")
btncatadd.setCheckable(True)
btncatadd.setStyleSheet("outline: none;")
btncatadd.clicked.connect(self.getnewcat)
   
btnprodadd = QPushButton("New Product")
btnprodadd.setCheckable(True)
btnprodadd.setStyleSheet("outline: none;")
#btnprodadd.clicked.connect(self.donewprod)
   
layoutg.addWidget(btncatadd,0,0)
layoutg.addWidget(btnprodadd,0,1)
layoutg.addWidget(color.Color('white'),0,2)
layoutg.addWidget(color.Color('white'),0,3)
layoutg.addWidget(color.Color('white'),0,4)
layoutg.addWidget(color.Color('white'),0,5)

## Add the buttons to layoutv   
btnwidg = QWidget()
btnwidg.resize(700, 5)
btnwidg.setLayout(layoutg)
layoutv.addWidget(btnwidg)


## Open a database connection and get the product categories
dbf.dbConnect(self)

if not self.myconn.isOpen():
    self.myres = "Database Connection ERROR: \n %s" % self.myconn.lastError().databaseText()
    self.myconn.close()
    del self.myconn
    QSqlDatabase.removeDatabase(QSqlDatabase.database().connectionName())
else:
    ## List of categories and category ids
    catlist = []
    catidlist = []
    
    mypcqry = QSqlQuery()
    mypcqry.exec("select category_id, category_name from product_category order by category_name")
    
    ## Loop through the query results and add them to the lists
    while mypcqry.next():
        catidlist.append(mypcqry.value(0))
        catlist.append(mypcqry.value(1))

    mypcqry.finish()

## Create the category tabs
self.pcats = QTabWidget()

## Loop through the category list to create the categories tabs and products grid
for pcat in catlist:
    self.layoutpgb = QGridLayout() ## Grid layout for the products
    layoutpv = QVBoxLayout()

    ## List for selected products
    self.selprods = []

    ## Create a scrollable list of products
    pscroll = QScrollArea()
    pscroll.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
    pscroll.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
    pscroll.setWidgetResizable(True)

    ## Row counter as variable number of rows returned from database
    myrow = 0
            
    ## Add the column headers
    self.layoutpgb.addWidget(QLabel("\n\nName"), myrow, 1)
    self.layoutpgb.addWidget(QLabel("Default\nBatch\nSize"), myrow, 2)
    self.layoutpgb.addWidget(QLabel("Production\nCost\nEach"), myrow, 3)
    self.layoutpgb.addWidget(QLabel("Recommended\nWholesale\nPrice"), myrow, 4)
    self.layoutpgb.addWidget(QLabel("Recommended\nRetail\nPrice"), myrow, 5)
    self.layoutpgb.addWidget(QLabel("\nLot\nNumber"), myrow, 6)
    self.layoutpgb.addWidget(QLabel("\nLot\nDate"), myrow, 7)

    ## Get the category id
    pcatid = catlist.index(pcat)
    pcatid = catidlist[pcatid]
    
    mypqry = QSqlQuery()
    mypqry.exec("select products_id,name,batch_size,cost_each,wholesale_price_each,retail_price_each,lot_number,manufacture_date from products where category = %s order by name" % (pcatid))

    ## Widget to hold the products category name
    prodcat = QWidget()

    ## Loop through the query results, adding each product to the grid
    while mypqry.next():
        myrow = myrow + 1

        ## Create the checkbox
        self.pchk = QCheckBox("{}".format(mypqry.value(1)), self)
        self.pchk.stateChanged.connect(lambda:onClicked(self))
        self.layoutpgb.addWidget(self.pchk, myrow, 1)
        
        self.layoutpgb.addWidget(QLabel(str(mypqry.value(2))), myrow, 2)
        self.layoutpgb.addWidget(QLabel(str(mypqry.value(3))), myrow, 3)
        self.layoutpgb.addWidget(QLabel(str(mypqry.value(4))), myrow, 4)
        self.layoutpgb.addWidget(QLabel(str(mypqry.value(5))), myrow, 5)
        self.layoutpgb.addWidget(QLabel(str(mypqry.value(6))), myrow, 6)

        dq = QDate(mypqry.value(7))
        ds = dq.toString("dd MMM yyyy")
        self.layoutpgb.addWidget(QLabel(ds), myrow, 7)

    mypqry.finish()

    ## If data returned add it to layoutv; otherwise, let the user know
    ## there are no products for the category
    if myrow > 0:
        mypwidg = QWidget()
        mypwidg.setLayout(self.layoutpgb)
        pscroll.setWidget(mypwidg)
        layoutpv.addWidget(pscroll)
    else:
        layoutpv.addWidget(QLabel("No products found"))

    ## Add the category tabs to layoutv
    prodcat.setLayout(layoutpv)
    self.pcats.addTab(prodcat, "%s" % (pcat))
               
dbf.dbCloseConnection(self)
layoutv.addWidget(self.pcats)

self.tab1.setLayout(layoutv)

def onClicked(self):
for x in range(self.layoutpgb.count()):
    if isinstance(self.layoutpgb.itemAt(x).widget(), QCheckBox):
        print("HERE x: %s" % x)
        if self.layoutpgb.itemAt(x).widget().isChecked():
            print("Checked x: %s" % x)
            #print(self.layoutpgb.itemAt(x).widget().text())
        else:
            print("Not Checked x: %s" % x)

运行时,我无法识别所选的QCHECKBOX。

Need some guidance on adding multiple QCheckBox items to a QGridLayout in a while loop that is processing data returned from a database.

I have created a window with tabs that identify product categories. Each tab contains a grid layout of products. Each product has a checkbox where it can be selected for further processing.

My windows looks like this:

Image of products window

My code to create the window is (I've italicized the area where I am having a problem):

def prodTab(self):
self.resize(950,400)
## Products tab
layoutv = QVBoxLayout() ## Main area layout
layoutg = QGridLayout() ## Layout for the top button area

## Main function buttons
btncatadd = QPushButton("New Category")
btncatadd.setCheckable(True)
btncatadd.setStyleSheet("outline: none;")
btncatadd.clicked.connect(self.getnewcat)
   
btnprodadd = QPushButton("New Product")
btnprodadd.setCheckable(True)
btnprodadd.setStyleSheet("outline: none;")
#btnprodadd.clicked.connect(self.donewprod)
   
layoutg.addWidget(btncatadd,0,0)
layoutg.addWidget(btnprodadd,0,1)
layoutg.addWidget(color.Color('white'),0,2)
layoutg.addWidget(color.Color('white'),0,3)
layoutg.addWidget(color.Color('white'),0,4)
layoutg.addWidget(color.Color('white'),0,5)

## Add the buttons to layoutv   
btnwidg = QWidget()
btnwidg.resize(700, 5)
btnwidg.setLayout(layoutg)
layoutv.addWidget(btnwidg)


## Open a database connection and get the product categories
dbf.dbConnect(self)

if not self.myconn.isOpen():
    self.myres = "Database Connection ERROR: \n %s" % self.myconn.lastError().databaseText()
    self.myconn.close()
    del self.myconn
    QSqlDatabase.removeDatabase(QSqlDatabase.database().connectionName())
else:
    ## List of categories and category ids
    catlist = []
    catidlist = []
    
    mypcqry = QSqlQuery()
    mypcqry.exec("select category_id, category_name from product_category order by category_name")
    
    ## Loop through the query results and add them to the lists
    while mypcqry.next():
        catidlist.append(mypcqry.value(0))
        catlist.append(mypcqry.value(1))

    mypcqry.finish()

## Create the category tabs
self.pcats = QTabWidget()

## Loop through the category list to create the categories tabs and products grid
for pcat in catlist:
    self.layoutpgb = QGridLayout() ## Grid layout for the products
    layoutpv = QVBoxLayout()

    ## List for selected products
    self.selprods = []

    ## Create a scrollable list of products
    pscroll = QScrollArea()
    pscroll.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
    pscroll.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
    pscroll.setWidgetResizable(True)

    ## Row counter as variable number of rows returned from database
    myrow = 0
            
    ## Add the column headers
    self.layoutpgb.addWidget(QLabel("\n\nName"), myrow, 1)
    self.layoutpgb.addWidget(QLabel("Default\nBatch\nSize"), myrow, 2)
    self.layoutpgb.addWidget(QLabel("Production\nCost\nEach"), myrow, 3)
    self.layoutpgb.addWidget(QLabel("Recommended\nWholesale\nPrice"), myrow, 4)
    self.layoutpgb.addWidget(QLabel("Recommended\nRetail\nPrice"), myrow, 5)
    self.layoutpgb.addWidget(QLabel("\nLot\nNumber"), myrow, 6)
    self.layoutpgb.addWidget(QLabel("\nLot\nDate"), myrow, 7)

    ## Get the category id
    pcatid = catlist.index(pcat)
    pcatid = catidlist[pcatid]
    
    mypqry = QSqlQuery()
    mypqry.exec("select products_id,name,batch_size,cost_each,wholesale_price_each,retail_price_each,lot_number,manufacture_date from products where category = %s order by name" % (pcatid))

    ## Widget to hold the products category name
    prodcat = QWidget()

    ## Loop through the query results, adding each product to the grid
    while mypqry.next():
        myrow = myrow + 1

        ## Create the checkbox
        self.pchk = QCheckBox("{}".format(mypqry.value(1)), self)
        self.pchk.stateChanged.connect(lambda:onClicked(self))
        self.layoutpgb.addWidget(self.pchk, myrow, 1)
        
        self.layoutpgb.addWidget(QLabel(str(mypqry.value(2))), myrow, 2)
        self.layoutpgb.addWidget(QLabel(str(mypqry.value(3))), myrow, 3)
        self.layoutpgb.addWidget(QLabel(str(mypqry.value(4))), myrow, 4)
        self.layoutpgb.addWidget(QLabel(str(mypqry.value(5))), myrow, 5)
        self.layoutpgb.addWidget(QLabel(str(mypqry.value(6))), myrow, 6)

        dq = QDate(mypqry.value(7))
        ds = dq.toString("dd MMM yyyy")
        self.layoutpgb.addWidget(QLabel(ds), myrow, 7)

    mypqry.finish()

    ## If data returned add it to layoutv; otherwise, let the user know
    ## there are no products for the category
    if myrow > 0:
        mypwidg = QWidget()
        mypwidg.setLayout(self.layoutpgb)
        pscroll.setWidget(mypwidg)
        layoutpv.addWidget(pscroll)
    else:
        layoutpv.addWidget(QLabel("No products found"))

    ## Add the category tabs to layoutv
    prodcat.setLayout(layoutpv)
    self.pcats.addTab(prodcat, "%s" % (pcat))
               
dbf.dbCloseConnection(self)
layoutv.addWidget(self.pcats)

self.tab1.setLayout(layoutv)

def onClicked(self):
for x in range(self.layoutpgb.count()):
    if isinstance(self.layoutpgb.itemAt(x).widget(), QCheckBox):
        print("HERE x: %s" % x)
        if self.layoutpgb.itemAt(x).widget().isChecked():
            print("Checked x: %s" % x)
            #print(self.layoutpgb.itemAt(x).widget().text())
        else:
            print("Not Checked x: %s" % x)

When run, I am unable to identify the selected QCheckBox.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文