使用 move() 方法 PyQt5 时 QPushButon 不显示

Posted

技术标签:

【中文标题】使用 move() 方法 PyQt5 时 QPushButon 不显示【英文标题】:QPushButon not showing when using move() method PyQt5 【发布时间】:2017-06-11 05:08:09 【问题描述】:

我有一个应该重现声音的简单窗口,当我创建 QPushButton 时,它会按预期显示在左上角,但是当我在其中任何一个上使用 move() 时,它们只是不再出现在窗口中。

class MainWindow(QMainWindow):
def __init__(self):
    super().__init__()
    self.setup()
def setup(self):
    self.musica = QSound('sounds/gorillaz.mp3')
    self.centralwidget = QWidget(self)
    self.boton = QPushButton(self.centralwidget)
    self.boton.setText('Reproducir')
    # self.boton.move(300, 100)
    self.boton2 = QPushButton(self.centralwidget)
    self.boton2.clicked.connect(self.musica.play)
    self.boton2.setText('DETENER')
    self.boton2.move(400, 100)
    self.boton2.clicked.connect(self.musica.stop)
    self.setWindowTitle('PrograPoP')
    self.resize(750,600)

为什么会这样?也许我应该使用另一种方法?

【问题讨论】:

【参考方案1】:

也许我应该使用另一种方法?

是的,您几乎应该总是使用Qt's layout mechanism。我在下面转换了您的示例:

#!/usr/bin/env python #in newer versions is not necesarry I think, but it's always worth doing

from PyQt5.QtWidgets import (QApplication, QWidget, 
    QPushButton, QMainWindow, QVBoxLayout, QHBoxLayout)
from PyQt5.QtMultimedia import QSound

class MainWindow(QMainWindow):
def __init__(self):
    super().__init__()
    self.setup()

def setup(self):
    self.musica = QSound('sounds/gorillaz.mp3')
    self.mainWidget = QWidget(self)
    self.setCentralWidget(self.mainWidget)

    self.mainLayout = QVBoxLayout()
    self.mainWidget.setLayout(self.mainLayout)

    self.mainLayout.addSpacing(100) # Add some empty space above the buttons.
    self.buttonLayout = QHBoxLayout()
    self.mainLayout.addLayout(self.buttonLayout)

    self.boton = QPushButton(self.mainWidget)
    self.boton.setText('Reproducir')
    #self.boton.move(300, 100)
    self.buttonLayout.addWidget(self.boton)
    self.boton2 = QPushButton(self.mainWidget)
    self.boton2.clicked.connect(self.musica.play)
    self.boton2.setText('DETENER')
    #self.boton2.move(400, 100)
    self.buttonLayout.addWidget(self.boton2)
    self.boton2.clicked.connect(self.musica.stop)
    self.setWindowTitle('PrograPoP')
    self.resize(750,600)

def main():
    app = QApplication([])

    win = MainWindow()
    win.show()
    win.raise_()
    app.exec_()

if __name__ == "__main__":
    main()

请注意,我将您的centralWidget 重命名为mainWidget,否则self.centralWidget = QWidget(self) 行会覆盖QMainWindow.centralWidget 方法定义,这会给您一个错误。

【讨论】:

谢谢,那太好了,但是如果我需要移动到某个像素位置呢?我可以在一个小部件中拥有多个布局吗?因为,据我了解,你申请的是横向的 小部件的位置(和大小)通常取决于窗口的大小。在不使用布局的情况下,每当窗口调整大小时,您都必须自己重新计算。这是布局为您提供的功能,这就是您(几乎)总是使用它们的原因。您可以通过 addLayout 方法使用嵌套布局。我已经更新了我的示例。其他选项是使用QGridLayout

以上是关于使用 move() 方法 PyQt5 时 QPushButon 不显示的主要内容,如果未能解决你的问题,请参考以下文章

pyqt5 -—-布局管理

PyQt5编程(9):窗口在屏幕的位置与管理

每次单击按钮时移动一个标签 PyQt5

PyQt5(01)Hello,PyQt5!

PyQt5 closeEvent 方法

pyqt5点击按钮从本地加载图片并显示在界面上