PyQt5 - 在 QTextEdit 的右上角放置一个小部件
PyQt5 - Position a widget at top right corner of a QTextEdit
我正在用 pyqt5 开发一个文本编辑器,我想实现一个像这样固定在我的文本区域右上角的查找框:
图片
textarea = QTextEdit()
layout = QHBoxLayout() # tried hbox, vbox and grid
find_box = QLineEdit()
empty = QTabWidget()
layout.addWidget(empty)
layout.addWidget(empty)
layout.addWidget(find_box)
textarea.setLayout(layout)
因此,使用此代码,即使 window 调整大小时,我也设法让我的 Find Box 粘在我的 texarea 的左侧。但不知何故,我的文本区域布局的 y 位置从中间开始:
图片
一个糟糕的解决方案是将 textarea 设置为我的 Find Box parent,使用 move(x, y) 来设置 Find Box 的位置但是我必须在我的 window 或我的 textarea 得到调整大小并再次使用 move() 设置新位置。
那么为什么我的 QTextEdit 的布局从中间开始?无论如何可以避免这种情况?
我通过使用 gridlayout
并将拉伸因子设置为行和列来实现它。
from PyQt5.QtWidgets import *
import sys
class Wind(QWidget):
def __init__(self):
super().__init__()
self.setupUI()
def setupUI(self):
self.setGeometry(300,300, 300,500)
self.show()
text_area= QTextEdit()
find_box = QLineEdit()
# this layout is not of interest
layout = QVBoxLayout(self)
layout.addWidget(text_area)
# set a grid layout put stuff on the text area
self.setLayout(layout)
text_layout= QGridLayout()
# put find box in the top right cell (in a 2 by 2 grid)
text_layout.addWidget(find_box, 0, 1)
# set stretch factors to 2nd row and 1st column so they push the find box to the top right
text_layout.setColumnStretch(0, 1)
text_layout.setRowStretch(1, 1)
text_area.setLayout(text_layout)
def main():
app= QApplication(sys.argv)
w = Wind()
exit(app.exec_())
if __name__ == '__main__':
main()
我正在用 pyqt5 开发一个文本编辑器,我想实现一个像这样固定在我的文本区域右上角的查找框:
图片
textarea = QTextEdit()
layout = QHBoxLayout() # tried hbox, vbox and grid
find_box = QLineEdit()
empty = QTabWidget()
layout.addWidget(empty)
layout.addWidget(empty)
layout.addWidget(find_box)
textarea.setLayout(layout)
因此,使用此代码,即使 window 调整大小时,我也设法让我的 Find Box 粘在我的 texarea 的左侧。但不知何故,我的文本区域布局的 y 位置从中间开始:
图片
一个糟糕的解决方案是将 textarea 设置为我的 Find Box parent,使用 move(x, y) 来设置 Find Box 的位置但是我必须在我的 window 或我的 textarea 得到调整大小并再次使用 move() 设置新位置。
那么为什么我的 QTextEdit 的布局从中间开始?无论如何可以避免这种情况?
我通过使用 gridlayout
并将拉伸因子设置为行和列来实现它。
from PyQt5.QtWidgets import *
import sys
class Wind(QWidget):
def __init__(self):
super().__init__()
self.setupUI()
def setupUI(self):
self.setGeometry(300,300, 300,500)
self.show()
text_area= QTextEdit()
find_box = QLineEdit()
# this layout is not of interest
layout = QVBoxLayout(self)
layout.addWidget(text_area)
# set a grid layout put stuff on the text area
self.setLayout(layout)
text_layout= QGridLayout()
# put find box in the top right cell (in a 2 by 2 grid)
text_layout.addWidget(find_box, 0, 1)
# set stretch factors to 2nd row and 1st column so they push the find box to the top right
text_layout.setColumnStretch(0, 1)
text_layout.setRowStretch(1, 1)
text_area.setLayout(text_layout)
def main():
app= QApplication(sys.argv)
w = Wind()
exit(app.exec_())
if __name__ == '__main__':
main()