首页 > 解决方案 > PyQt4 将 LineEdit 拉伸到窗口宽度

问题描述

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

必须添加什么才能将其拉伸到整个窗口宽度并使其与窗口保持可伸缩性?

标签: pythonpyqtpyqt4

解决方案


无效 QWidget::resizeEvent(QResizeEvent *事件)

此事件处理程序可以在子类中重新实现,以接收在事件参数中传递的小部件调整大小事件。当调用 resizeEvent() 时,小部件已经有了它的新几何图形。

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

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

在此处输入图像描述


推荐阅读