ceh358
ceh358

Reputation: 53

How to make a button move as the window size is adjusted? (PyQt4)

I know the 2nd line I commented out doesn't work, just a representation of what I was thinking. This would be running the whole time the program is, so it could adjust to size changes.

Is something like this possible?

import sys    
from PyQt4 import QtGui, QtCore

class Window(QtGui.QMainWindow):
    def __init__(self):
        super(Window, self).__init__()
        self.setGeometry(50, 50, 500, 300)
        self.setWindowTitle("SciCalc")
        self.setWindowIcon(QtGui.QIcon('atom.png'))
        # self.setFixedSize(1000,800)
        self.home()

    def home(self):
        btn = QtGui.QPushButton("Physics", self)
        btn.clicked.connect(QtCore.QCoreApplication.instance().quit)
        btn.resize(100, 100)
        btn.resize(100, 100)
        # btn.move(width/2,height/2)
        self.show()


def run():
    app = QtGui.QApplication(sys.argv)
    GUI = Window()
    sys.exit(app.exec_())


run()

Upvotes: 2

Views: 1631

Answers (1)

eyllanesc
eyllanesc

Reputation: 243887

Assuming that what you want is that the button stays in the middle of the window always, that you could do it by overwriting the resizeEvent method.

import sys    
from PyQt4 import QtGui, QtCore

class Window(QtGui.QMainWindow):
    def __init__(self):
        super(Window, self).__init__()
        self.setGeometry(50, 50, 500, 300)
        self.setWindowTitle("SciCalc")
        self.setWindowIcon(QtGui.QIcon('atom.png'))
        self.home()

    def home(self):
        self.btn = QtGui.QPushButton("Physics", self)
        self.btn.clicked.connect(QtCore.QCoreApplication.instance().quit)
        self.btn.resize(100, 100)
        self.show()

    def resizeEvent(self, event):
        self.btn.move(self.rect().center()-self.btn.rect().center())
        QtGui.QMainWindow.resizeEvent(self, event)


def run():
    app = QtGui.QApplication(sys.argv)
    GUI = Window()
    sys.exit(app.exec_())


run()

Upvotes: 3

Related Questions