Drag n Drop Button and Drop-down menu PyQt/Qt designer

前端 未结 4 2065
悲&欢浪女
悲&欢浪女 2020-12-11 11:27

I would like to know the \"best practice\" to change the behavior of some buttons to do the following:

I want with a click to appear a menu. Or when you drag this sa

4条回答
  •  余生分开走
    2020-12-11 11:49

    In order to add code to a UI generated with QtDesigner, you must generate a .py file using pyuic:

    pyuic myform.ui -o ui_myform.py
    

    This ui_myform.py file, contains generated code that you should not edit, so later you can change your .ui file with QtDesigner, re-run pyuic, and get ui_myform.py updated without loosing any work.

    The generated file will have a class Ui_myForm(object) (named after on your main widget's name), with a def setupUi(self, myForm) method inside. One way this can be used, is by creating your own class MyForm (on a separate file) which will inherit Ui_myForm, and some other Qt Class, like QWidget or QDialog:

    myform.py:

    from ui_myform import Ui_myForm
    from PyQt4.QtGui import QDialog
    
    class MyForm(QDialog, Ui_myForm):
    
        def __init__(self, parent = None):
            QDialog.__init__(self, parent)
    
            self.setupUi(self)    #here Ui_myForm creates all widgets as members 
                                  #of this object.
                                  #now you can access every widget defined in 
                                  #myForm as attributes of self   
    
            #supposing you defined two pushbuttons on your .UI file:
            self.pushButtonB.setEnabled(False)
    
            #you can connect signals of the generated widgets
            self.pushButtonA.clicked.connect(self.pushButtonAClicked)
    
    
    
        def bucar_actualizaciones(self):
            self.pushButtonB.setEnabled(True)
    

    The names of the widgets are the one you set on QtDesigner, but is easy to inspect ui_myform.py in order to see the available widgets and names.

    In order to use a custom widget in QtDesigner, you can right-click the button, and go to Promote to.... There you'l have to enter:

    • Base class name: QPushButton for example
    • Promoted class name: MyPushButton (this must be the name of the class of your custom widget)
    • Header file: mypushbutton.h. This will be converted to .py by pyuic.

    Click Add and then Promote.

    When you run pyuic, it will add this line at the end of ui_myform.py

    from mypushbutton import MyPushButton
    

    Also, you'll see that the generated code used MyPushButton instead of QPushButton

提交回复
热议问题