2

so I was wondering how I could make a subclass of a widget For example if I wanted to create a widget, that inherited methods and attributes from QtWidgets.QPushButton, however I would create extra methods and attributes on top of that.

class Coord(QtWidgets.QPushButton):
    def __init__(self):
        super(Coord, self).__init__()
        self.coordinates = []
        #basically adding attributes to the object "QPushButton"

    def set_text(self,text):
        self.setText(text)
        chrcount = 100 / len(text)
        self.setStyleSheet("font-size: {}".format(chrcount))
        #This will set the text of the button, yet will resize it appropriatly

This is an example. However, it creates the "button" widget as a new window. I was wondering how I could get it to act like QPushButton would anyway, just with the extra features I'd like to add to it

Edit: Fixed- replaced my "super" function from

def __init__(self):
    super(Coord, self).__init__()

to

def __init__(self,parent):
    super(Coord, self).__init__(parent)

Don't really know how that fixed it but hey ho!

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
Tom Bell
  • 29
  • 3
  • I was about to answer with exactly your fix. Objects in Qt need parents. I recommend a review of QObject's documentation, and probably the Layout API overview, too. – jonspaceharper Mar 12 '18 at 20:04
  • I knew I was missing somthing because of the difference between QtWidgets.QPushButtin(self) and how Coord() lacked a "self" – Tom Bell Mar 12 '18 at 20:07
  • 2
    @TomBell Your question as this is unsolvable for others since you do not show the context where that problem is generated, so it falls in the off-topic "why is this code not working?", Only you were able to solve it since you had the code necessary to reproduce your error, we do not. I recommend that for a next question read [ask] and provide if necessary, as in this case, a [mcve] – eyllanesc Mar 12 '18 at 20:17
  • Possible duplicate of [PyQt: give parent when creating a widget?](https://stackoverflow.com/questions/37918012/pyqt-give-parent-when-creating-a-widget) – Skandix Mar 13 '18 at 22:18

1 Answers1

0

you can use the qt designer to create a button and set all possible features of a button there. If that is not enough you can adjust the button in your coding like self.button.whatever.set....If that is not enough attache the button to a class in qt designer, create a module and a class and do adjust whatever you want.

accpert.com
  • 109
  • 11