简体   繁体   English

如何将特殊功能分配给字典 PyQt 中的工具栏操作元素?

[英]How to assign special functions into a toolbar action element from dictionary PyQt?

I am taking the data from the excel file with pandas.我正在使用 pandas 从 excel 文件中获取数据。

I created a dictionary which includes the same length of my excel data.我创建了一个字典,其中包含相同长度的 excel 数据。 mat_id_list

class MainWindow(QMainWindow):

    def __init__(self):
        super(MainWindow, self).__init__()
        
        
        self.setWindowTitle("Chart")

        self.button_dir={i:[0,0] for i in range(len(mat_id_list))}

        # print(button_dir)

        toolbar = QToolBar("My main toolbar")
        
        self.addToolBar(toolbar)
        
        for i in range(len(mat_id_list)):
            
            self.button_dir[i][0]=QAction(mat_id_list[i],self)
            self.button_dir[i][1]=print_id(i)
            
            self.button_dir[i][0].triggered.connect(lambda :self.button_dir[i][1])
            
            toolbar.addAction(self.button_dir[i][0])

        print(self.button_dir)        
               
        # print((self.agroup). checkedId())

    def print_id(self,i):
        print(mat_id_list[i])
        

Toolbar method works great with loop to create Buttons on toolbar but i can not assign specific function with for loop into my buttons or action.(I dont know how to call object name on the toolbar)工具栏方法非常适合循环在工具栏上创建按钮,但我无法将特定的 function 与 for 循环分配到我的按钮或操作中。(我不知道如何在工具栏上调用 object 名称)

在此处输入图像描述

Here down below: I thought that, i can create second index to fill a function in dictionary element to call it later with the click action happens.在下面:我认为,我可以创建第二个索引来填充字典元素中的 function,以便稍后在单击操作发生时调用它。

self.button_dir={i:[0,0] for i in range(len(mat_id_list))}

Related below:相关如下:

 self.button_dir[i][0].triggered.connect(lambda :self.button_dir[i][1])

My Goal is to define functions into the buttons on the toolbar that will give me the result of my function.我的目标是将功能定义到工具栏上的按钮中,这将给我 function 的结果。

def print_id(self,i):
   print(mat_id[i])

"i" is the index number in the for loop. “i”是 for 循环中的索引号。

According to @ekhumoro's advice:根据@ekhumoro 的建议:

class MainWindow(QMainWindow):

    def __init__(self):
        super(MainWindow, self).__init__()
        
        
        self.setWindowTitle("Chart")

        toolbar = QToolBar("My main toolbar")
        
        self.addToolBar(toolbar)
        
        for i in range(len(mat_id_list)):
            
            action=QAction(mat_id_list[i],self)
            action.triggered.connect(lambda x, i=i:
                                     self.print_id(i))
            toolbar.addAction(action

    def print_id(self,i):
        print(mat_id_list[i])
        
if __name__ == '__main__':
    app = QApplication(sys.argv)

    demo = MainWindow()
    demo.show()

    sys.exit(app.exec_())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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