2017-06-11 127 views
0

我有一个应该重现声音的简单窗口,当我创建QPushButton时,它会在左上角显示它应该的样子,但是当我使用移动()其中的任何一个,他们只是不会在窗口中显示anymoer。QPushButon在使用move()方法时没有显示PyQt5

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) 

这是怎么发生的?也许有另一种方法我应该使用?

回答

0

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

是的,你应该几乎总是使用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() 

请注意,我改名您centralWidgetmainWidget,否则self.centralWidget = QWidget(self)覆盖QMainWindow.centralWidget方法定义,它会给你一个错误的行。

+0

谢谢,这很好,但如果我需要移动到某个像素位置?我可以在Widget中使用多个布局吗?因为,据我所知,你应用的是水平的一个 – gramsch

+0

你的小部件的位置(和大小)通常取决于窗口的大小。无需使用布局,只要窗口调整大小,您就必须自行重新计算。这是布局为您提供的功能,这就是您(几乎)始终使用它们的原因。您可以使用'addLayout'方法使用嵌套布局。我已更新我的示例。其他选项是使用'QGridLayout' – titusjan

相关问题