python - PyQt5 - 将小部件放置在 QTextEdit 的右上角

标签 python pyqt pyqt5 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)

因此,通过这段代码,我设法让我的查找框粘在我的 texarea 的左侧,即使窗口大小被调整。但不知何故,我的文本区域布局的 y 位置从中间开始:

图片

一个糟糕的解决方案是将文本区域设置为我的查找框父级,使用 move(x, y) 来设置查找框的位置,但每当我的窗口或文本区域调整大小时我都必须捕获并使用 move()再次设置新位置。

那么为什么我的 QTextEdit 的布局从中间开始呢?有什么办法可以避免这种情况吗?

最佳答案

我通过使用gridlayout并为行和列设置拉伸(stretch)因子来使其工作。

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

关于python - PyQt5 - 将小部件放置在 QTextEdit 的右上角,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45962073/

相关文章:

python - 如何使用 PyQt5.QWebkitWidgets 在我的 QtGui 中显示谷歌地图

python - 组合两列给出 ValueError : Wrong number of items passed 2, placement implies 1

python - 比较 pandas/numpy 中的 NaN 列

python - Qt - 暂时禁用所有事件或窗口功能?

python - 如何更改标签、行编辑等相对于窗口大小的位置?

python - PyQt5。对话框窗口不显示。改为关闭主窗口

python-3.x - PyInstaller; "could not find or load the Qt platform plugin "Windows”

python - 如何从 QNetworkCookieJar 转换为字符串 dict 或 requests.cookie?

python - 在 Fabric (Python) 中自动创建 SSL

python - 有没有办法清除 QListWïdget 中除 1 个特定行之外的所有行