我想将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()
必须添加哪些内容才能将其拉伸到整个窗口宽度,并使其随窗口可伸缩?
答案 0 :(得分: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)
# ...
答案 1 :(得分: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()
如果要消除侧面的空间,只需将这些边距设置为零(尽管我更喜欢使用边距,因为它更美观):
lay.setContentsMargins(0, 0, 0, 0)