PyQt4将QLineEdit拉伸到窗口宽度

问题描述 投票:2回答:2

我想将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()

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

python pyqt pyqt4
2个回答
2
投票

使用布局:

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

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

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

enter image description here


2
投票

void QWidget :: resizeEvent(QResizeEvent * event)

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

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

© www.soinside.com 2019 - 2024. All rights reserved.