簡體   English   中英

PyQt4將LineEdit拉伸到窗口寬度

[英]PyQt4 stretch LineEdit to window width

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

必須添加哪些內容才能將其拉伸到整個窗口寬度並保持其隨窗口可縮放?

無效的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)
# ...

在此處輸入圖片說明

使用布局:

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

在此處輸入圖片說明

如果要消除側面的空間,只需要將這些邊距設置為零(盡管我更喜歡使用邊距,因為它更美觀):

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

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM