Custom button PyQT4

2019-09-06 21:07发布

问题:

I'm having trouble displaying a button that I create from a class in PyQt4, using Python 2.7. My project has 80 buttons that all require a drag and drop function. I've created a button class that allows this, but I'm unsure as to how to display it within Ui_Form.

I don't think I can use a layout manager as I want a background image so I assume I need to create the button from the Button class using the Form argument from Ui_Form's setupUi function, but I'm insure as to how.

Below is an example of the script with only two buttons (and a screenshot)- one called from my class and one just as QT Designer left it. The button btn_a1 should be visible to the left of btn_a2, but it isn't (due to not knowing how to properly call it). I've removed the code for the labels and functionality of the buttons to help with ease of use.

import sys
from PyQt4 import QtCore, QtGui

class Ui_Form(QtGui.QWidget):
    def __init__(self):
        QtGui.QWidget.__init__(self)
        self.setupUi(self)

    def setupUi(self, Form):
        Form.setObjectName("Form")
        Form.resize(591, 591)
        self.Background = QtGui.QLabel(Form)
        self.Background.setGeometry(QtCore.QRect(0, 0, 631, 591))
        self.Background.setPixmap(QtGui.QPixmap("Python/LP_Proj/LP_Background.png"))
        self.Background.setObjectName("Background")

        self.btn_a1 = Button(Form)

        self.btn_a2 = QtGui.QPushButton(Form)
        self.btn_a2.setGeometry(QtCore.QRect(90, 40, 41, 41))
        self.btn_a2.setObjectName("btn_a2")

        self.retranslateUi(Form)
        QtCore.QMetaObject.connectSlotsByName(Form)

    def retranslateUi(self, Form):
        Form.setWindowTitle(QtGui.QApplication.translate("Form", "Launchpad Control", None, QtGui.QApplication.UnicodeUTF8))

class Button(QtGui.QPushButton):
    def __init__(self, Form):
        super(Button, self).__init__()
        self.setAcceptDrops(True)

        self.setGeometry(QtCore.QRect(30, 40, 41, 41))
        self.setObjectName("btn_a1")

if __name__=='__main__':
    app = QtGui.QApplication(sys.argv)
    ex = Ui_Form()
    ex.show()
    sys.exit(app.exec_())

回答1:

A slight modification is required in your Button class:

def __init__(self, text='', parent=None):
    super(Button, self).__init__('Text', parent=parent)
    ...

Then in your setupUi method in Ui_Form change

self.btn_a1 = Button(Form)

to

self.btn_a1 = Button('Text', self)

The UI now looks like this: