2017-06-11 34 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

相關問題