PyQt4 将 LineEdit 拉伸到 window 宽度

PyQt4 stretch LineEdit to window width

我想将 QLineEdit 小部件拉伸到 window 宽度。
这是要拉伸的小部件的代码 <---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()

必须添加什么才能将其拉伸到整个 window 宽度并保持其可缩放 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)
# ...

使用布局:

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

如果你想消除边上的space,只需要将这些边距设置为零(虽然我更喜欢有边距的,因为它更美观):

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