smajli
smajli

Reputation: 351

PyQt4 stretch LineEdit to window width

I would like to stretch the QLineEdit widget to window width.
Here is the code with widget to be stretched marked <---HERE

import sys
from PyQt4.Qt import *

# Create the QApplication object
qt_app = QApplication(sys.argv)

class HWApp(QWidget):
    ''' Basic Qt app'''
    def __init__(self):
        # Initialize the object as a QLabel
        QWidget.__init__(self) #, "Hello, world!")

        # Set the size, alignment, and title
        self.setMinimumSize(QSize(800, 600))

        self.setWindowTitle('Hello, world!')
        self.tbox = QLineEdit("simple text",self)#<---HERE
        self.setAlignment(Qt.AlignCenter)

    def run(self):
        ''' Show the app window and start the main event loop '''
        self.show()
        qt_app.exec_()

# Create an instance of the app and run it
HWApp().run()

What has to be added to stretch it to whole window width and keep it scalable with window?

Upvotes: 2

Views: 1173

Answers (2)

eyllanesc
eyllanesc

Reputation: 244282

Use a layout:

import sys
from PyQt4.Qt import *

# Create the QApplication object
qt_app = QApplication(sys.argv)

class HWApp(QWidget):
    ''' Basic Qt app'''
    def __init__(self):
        # Initialize the object as a QLabel
        QWidget.__init__(self) #, "Hello, world!")

        # Set the size, alignment, and title
        self.setMinimumSize(QSize(800, 600))

        self.setWindowTitle('Hello, world!')
        self.tbox = QLineEdit("simple text", alignment=Qt.AlignCenter) # <---HERE
        lay = QVBoxLayout(self)
        lay.addWidget(self.tbox)
        lay.addStretch()

    def run(self):
        ''' Show the app window and start the main event loop '''
        self.show()
        qt_app.exec_()

# Create an instance of the app and run it
HWApp().run()

enter image description here

If you want to eliminate the space on the sides, it is only necessary to set those margins to zero (Although I prefer preferring it with margins since it is more aesthetic):

lay.setContentsMargins(0, 0, 0, 0)

enter image description here

Upvotes: 2

S. Nick
S. Nick

Reputation: 13691

void QWidget::resizeEvent(QResizeEvent *event)

This event handler can be reimplemented in a subclass to receive widget resize events which are passed in the event parameter. When resizeEvent() is called, the widget already has its new geometry.

# ...
    self.tbox = QLineEdit("simple text", self)            # <---HERE
    self.tbox.setAlignment(Qt.AlignCenter)                # +++

def resizeEvent(self, event):                             # +++
    self.tbox.resize(self.width(), 30)
# ...

enter image description here

Upvotes: 2

Related Questions