PyQT5:即使在使用网格后,Qlabel 也会相互叠加

PyQT5 : Qlabel overlay eachother even after using grid

我是新手,我只想学习如何编写一些代码 UI。我对 PyQt5 的问题如下。

我只创建了 3 个标签(每个命名标签、label1 和 label2)。一个应该只包含文本,另一个应该打印时间,第三个应该打印鼠标的位置 (x, y)。

当我使用网格布局时,即使我使用网格添加小部件指定了不同的位置,它也只会在同一位置打印 Qlabels。

感谢任何帮助。提前谢谢你。

我的代码:

#Source : 
import sys
from PyQt5.QtWidgets import (QMainWindow, QWidget, QLabel, QApplication, QToolTip, QPushButton, 
                             QMessageBox, QGridLayout, QHBoxLayout, QVBoxLayout, QTextEdit)
from PyQt5.QtGui import QIcon, QFont
from PyQt5.QtCore import Qt, QTime

class BgColorExperiment(QMainWindow):
    def __init__(self):
        super().__init__()
        # moves the widget to a position on the screen at x=300, y=300 coordinates
        self.left = 300
        self.top  = 300
        # resizes the widget (250px wide and 150px high) 
        self.width  = 450
        self.height = 450
        # title of Widget shown in the titlebar
        self.title ='Suivi des BDs crées'
        # sets the application icon
        self.setWindowIcon(QIcon('suivibdicon.png'))
        # Set the status bar
        self.statusBar().showMessage('Engineered by idiots')
        # parent
        self.init_ui()

    def init_ui(self):
        # Artiste
        self.setObjectName('MainWidget')
        self.setStyleSheet("""
            #MainWidget {
                background-color: #333;
                }
            .QLabel{
                color: green;
                background-color: #333;
                selection-color: yellow;
                selection-background-color: blue;
                font-family : Consolas;
                font-size: 10pt;
                }
            .QToolTip {
                background-color: #333;
                color: #fff;
                border: red solid 1px;
                opacity: 100;
                font-family : Consolas;
                font-size: 10pt;
                }
            .QMessageBox {
                background-color: #333;
                }
            QStatusBar {
                color: green;
                font-family : Consolas;
                font-size: 10pt;
                }
        """)
        # violence
        self.label  = QLabel('position of the mouse', self)
        self.label1 = QLabel('some words 一些单词', self)
        self.label2 = QLabel('digital clock', self)

        grid = QGridLayout()

        # just blablabla
        grid.addWidget(self.label1, 0, 0)

        # Digital Clock
        grid.addWidget(self.label2, 1, 0)

        # Mouse tracking
        x, y = 0, 0
        self.text = "x: {0}, y: {1}".format(x, y)
        self.label = QLabel(self.text, self) # display the x and y coordinates of a mouse pointer in a label widget.
        grid.addWidget(self.label, 2, 0)
        self.setMouseTracking(True)

#        # push button widget and set a tooltip (useless)
#        #btn = QPushButton('Button', self)
#        #btn.setToolTip('This is a <b>QPushButton</b> widget for refresh')
#        #btn.resize(btn.sizeHint())
#        #hbox.addWidget(btn)

        # set the grid
        self.setLayout(grid)
        # set the window size using the setGeometry
        self.setGeometry(self.left, self.top, self.width, self.height)
        # set the window title
        self.setWindowTitle(self.title)
        self.show()                                 # displays the widget on the screen

    def closeEvent(self, event): # Define behavior when clicking on the x button on the title bar
        reply = QMessageBox.question(self, 'Message',  "Are you sure to quit?", QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
        if reply == QMessageBox.Yes:
            event.accept()
        else:
            event.ignore()

    def mouseMoveEvent(self, e): # for following the position of the mouse
        x, y = e.x(), e.y()
        text = "x: {0}, y: {1}".format(x, y)
        self.label.setText(text)

    def showTime(self): # for printing the time (format = 'hh:mm:ss')
        time = QTime.currentTime()
        text = time.toString('hh:mm:ss')
        self.label2.setText(text)

if __name__ == '__main__':
    APP = QApplication(sys.argv)
    EXP = BgColorExperiment()
    sys.exit(APP.exec_()) # mainloop of the application

无效QMainWindow::setCentralWidget(QWidget *widget)

将给定的小部件设置为主 window 的中央小部件。

注意:QMainWindow 获取小部件指针的所有权并在适当的时候将其删除。

import sys
from PyQt5.QtWidgets import (QMainWindow, QWidget, QLabel, QApplication, QToolTip, QPushButton, 
                             QMessageBox, QGridLayout, QHBoxLayout, QVBoxLayout, QTextEdit)
from PyQt5.QtGui  import QIcon, QFont
from PyQt5.QtCore import Qt, QTime

class BgColorExperiment(QMainWindow):
    def __init__(self):
        super().__init__()
        # moves the widget to a position on the screen at x=300, y=300 coordinates
        self.left = 300
        self.top  = 300
        # resizes the widget (250px wide and 150px high) 
        self.width  = 450
        self.height = 450
        # title of Widget shown in the titlebar
        self.title ='Suivi des BDs crées'
        # sets the application icon
        self.setWindowIcon(QIcon('suivibdicon.png'))
        # Set the status bar
        self.statusBar().showMessage('Engineered by idiots')
        # parent
        self.init_ui()

    def init_ui(self):
        # Artiste
        self.setObjectName('MainWidget')
        self.setStyleSheet("""
            #MainWidget {
                background-color: #333;
                }
            .QLabel{
                color: green;
                background-color: #333;
                selection-color: yellow;
                selection-background-color: blue;
                font-family : Consolas;
                font-size: 10pt;
                }
            .QToolTip {
                background-color: #333;
                color: #fff;
                border: red solid 1px;
                opacity: 100;
                font-family : Consolas;
                font-size: 10pt;
                }
            .QMessageBox {
                background-color: #333;
                }
            QStatusBar {
                color: green;
                font-family : Consolas;
                font-size: 10pt;
                }
        """)
        # violence
        self.label  = QLabel('position of the mouse', self)
        self.label1 = QLabel('some words 一些单词', self)
        self.label2 = QLabel('digital clock', self)

        centralWidget = QWidget()                         # +++++
        self.setCentralWidget(centralWidget)              # +++++

        grid = QGridLayout(centralWidget)                 # +++++ centralWidget

        # just blablabla
        grid.addWidget(self.label1, 0, 0)

        # Digital Clock
        grid.addWidget(self.label2, 1, 0)

        # Mouse tracking
        x, y = 0, 0
        self.text = "x: {0}, y: {1}".format(x, y)
        self.label = QLabel(self.text, self) # display the x and y coordinates of a mouse pointer in a label widget.
        grid.addWidget(self.label, 2, 0)
        self.setMouseTracking(True)

#        # push button widget and set a tooltip (useless)
#        #btn = QPushButton('Button', self)
#        #btn.setToolTip('This is a <b>QPushButton</b> widget for refresh')
#        #btn.resize(btn.sizeHint())
#        #hbox.addWidget(btn)

        # set the grid
#        self.setLayout(grid)                                          # -----
        # set the window size using the setGeometry
        self.setGeometry(self.left, self.top, self.width, self.height)
        # set the window title
        self.setWindowTitle(self.title)
        self.show()                                 # displays the widget on the screen

    def closeEvent(self, event): # Define behavior when clicking on the x button on the title bar
        reply = QMessageBox.question(self, 'Message',  "Are you sure to quit?", QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
        if reply == QMessageBox.Yes:
            event.accept()
        else:
            event.ignore()

    def mouseMoveEvent(self, e): # for following the position of the mouse
        x, y = e.x(), e.y()
        text = "x: {0}, y: {1}".format(x, y)
        self.label.setText(text)

    def showTime(self): # for printing the time (format = 'hh:mm:ss')
        time = QTime.currentTime()
        text = time.toString('hh:mm:ss')
        self.label2.setText(text)

if __name__ == '__main__':
    APP = QApplication(sys.argv)
    EXP = BgColorExperiment()
    sys.exit(APP.exec_()) # mainloop of the application