简体   繁体   中英

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?

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)
# ...

在此处输入图片说明

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()

在此处输入图片说明

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)

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM