SBarkovskis
SBarkovskis

Reputation: 124

PyQt label positioning on widget

I create an simple arduino project. The main purpose of my project is to display text on a LCD screen based on PIN status (1 or 0).

To reach this, i create a simple form and added a label on it. On startup it shows a default text, but when I press a menu button (simulate PIN =1) the text is changed to "WARNING_TEXT"

Here is my Python code (this is Entry point for my app):

import sys
from forms import MainForm2
import os
from PyQt4.QtGui import *


def main():
    app,  window = MainForm2.init()

    p = app.desktop().availableGeometry().center()
    window.move(p.x()-window.width()*0.5,p.y()-window.height()*0.5)
    window.setWindowTitle('Monitor') #<=Nazvanie app    
    window.showMaximized()
    sys.exit(app.exec_())

if __name__ =="__main__":
    main()

The code of MainForm2(all application logic is here):

# -*- coding: utf-8 -*-

from PyQt4 import QtGui,QtCore
from PyQt4.QtGui import QSizePolicy,QColor
import sys
import time

try:
    _fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
    def _fromUtf8(s):
        return s

try:
    _encoding = QtGui.QApplication.UnicodeUTF8
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig)

class QMainWindow(QtGui.QMainWindow):
    defaultStyle ='color:green;font-size:240px'
    warningStyle ='color:red;text-align: justify;font-size:{0}px'

    def __init__(self,parent=None):
        super(QtGui.QMainWindow,self).__init__(parent)
        self.cnfVacant = "Default text"
        self.cnfBusy = "Warning text"
        self.setupUi()

    def setupUi(self):
        self.thread=QMyThread()

        #timer
        self.timer = QtCore.QTimer()
        self.timer.setInterval(1000)
        self.timer.timeout.connect(self.displayTime)


        self.main = QtGui.QWidget(self)
        self.main.setAutoFillBackground(True)
        p = self.main.palette()
        p.setColor(self.main.backgroundRole(),QColor.fromRgb(0,0,0,255))
        self.main.setPalette(p)
        self.setCentralWidget(self.main)


        self.menubar = QtGui.QMenuBar(self)
        self.menubar.setGeometry(QtCore.QRect(0,0,559,25))
        #trigger
        self.menu_file_exit =QtGui.QAction(self.main)
        self.menu_file_exit.setText("Exit")

        self.menu_file_start = QtGui.QAction(self.main)
        self.menu_file_start.setText("Start")

        layout = QtGui.QGridLayout(self.main)

        self.label = QtGui.QLabel("",self.main)
        self.label.setText(_fromUtf8(self.cnfVacant.replace(" ","\n")))

        self.label.setStyleSheet(self.defaultStyle)
        self.label.setSizePolicy (QSizePolicy.Fixed,QSizePolicy.Expanding)
        self.label.setSizePolicy (QSizePolicy.Fixed,QSizePolicy.Expanding)



        layout.addWidget(self.label,10,10)
        layout.addWidget(self.lbl,50,50)

        self.connect(self.menu_file_exit, QtCore.SIGNAL('triggered()'), sys.exit)
        self.connect(self.menu_file_start,QtCore.SIGNAL('triggered()'),self.thread.run)

        QtCore.QObject.connect(self.thread,QtCore.SIGNAL('log(QString)'),self.tmp)

        self.menu_file = self.menubar.addMenu("File")
        self.menu_file.addAction(self.menu_file_start)
        self.menu_file.addAction(self.menu_file_exit)

        self.setMenuBar(self.menubar)
    def tmp(self,s):
        self.label.setText(_fromUtf8(self.cnfBusy))
        self.label.setWordWrap(True)
        self.label.setStyleSheet(self.warningStyle)
        self.label.setStyleSheet(self.warningStyle.format(self.cnfWarning[0]))
        print 'Hello sub {0}'.format(s)

    def displayTime(self):
        mDate=QtCore.QDateTime.currentDateTime().toString("dd.MM.yyyy")
        mTime=QtCore.QDateTime.currentDateTime().toString("HH:mm:ss")
        self.lbl.setText("{0} \n {1}".format(mDate,mTime))  

class QMyThread(QtCore.QThread):
    def __init__(self,parent=None):
        super(QtCore.QThread,self).__init__(parent)

    def run(self):
        i=0
        while True:
            i=i+1
            if(i==10):
                self.setLog("Hello from thread")
                time.sleep(0.3)
                break

    def setLog(self,text):
        self.emit(QtCore.SIGNAL('log(QString)'),QtCore.QString(text))

def init():
    app = QtGui.QApplication(sys.argv)
    MainWindow =QMainWindow()
    MainWindow.show()
    return app, MainWindow

With this code I get just one label centered on the form and with this I have two problems:

  1. long text are showing incorrect. Something like " bla bla blabla blablabla bla"

  2. How to get second label on the form in the right bottom corner?

I want to get similar like on the attached picture:

enter image description here

Can some one point me, how to do this?

Upvotes: 1

Views: 4836

Answers (1)

eyllanesc
eyllanesc

Reputation: 243887

Before going to the problem I will point out the improvements that your code can have:

  • Do not use the old style of connection, check the new style.
  • It is not necessary to write the constructor of a class that you inherit if you are not going to modify it.
  • You should not call the run() method of QThread directly, otherwise the task will run on the main thread, and obviously it does not have to be sent, you must call the start() method, this internally creates the thread and the run() method will execute on that thread. Keep in mind QThread is not a thread, it is a thread handler.
  • Do not use the same name of a class as the one you inherit, it could bring you problems that will be difficult to debug in the future.

Going to the point, it is only necessary to establish the first QLabel using the layout, and to center it use setAlignment() passing it QtCore.Qt.AlignCenter that tells it to focus horizontally and vertically.

The other QLabel that shows the time you must move it manually through the geometry, this must be done every time the QLabel is modified, so we use resizeEvent and the method that updates the text.

# -*- coding: utf-8 -*-

import sys
import time

from PyQt4 import QtGui, QtCore


try:
    _fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
    def _fromUtf8(s):
        return s

try:
    _encoding = QtGui.QApplication.UnicodeUTF8
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig)

defaultStyle ='color:green;font-size: 60px'
warningStyle ='color:red;text-align: justify;font-size:{0}px'

class MainWindow(QtGui.QMainWindow):
    def __init__(self, parent=None):
        QtGui.QMainWindow.__init__(self, parent)
        widget = QtGui.QWidget()
        self.setCentralWidget(widget)

        self.label = QtGui.QLabel("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas vitae laoreet erat. Donec eleifend erat sapien. Morbi velit est, pellentesque vel fringilla eget, rhoncus nec sem. Curabitur rutrum sodales luctus. Nulla vel aliquam leo. Pellentesque non ante at nisl pulvinar posuere vel vel orci.")
        self.label.setAlignment(QtCore.Qt.AlignCenter)
        self.label.setWordWrap(True)
        self.label.setStyleSheet(defaultStyle)

        pal = widget.palette()
        pal.setColor(widget.backgroundRole(), QtGui.QColor.fromRgb(0,0,0,255))
        widget.setPalette(pal)
        widget.setAutoFillBackground(True)


        self.lbl = QtGui.QLabel(widget)
        self.lbl.setStyleSheet("*{color:green; font-size:48px}")
        timer = QtCore.QTimer(self)
        timer.timeout.connect(self.displayTime)
        timer.start(1000)
        self.displayTime()

        menubar = QtGui.QMenuBar()
        self.setMenuBar(menubar)
        menu_file = menubar.addMenu("File")

        menu_file_exit = menu_file.addAction("Exit")
        menu_file_start = menu_file.addAction("Start")

        menu_file_exit.triggered.connect(self.close)

        self.mthread = QMyThread(self)
        self.mthread.log.connect(self.fun)

        menu_file_start.triggered.connect(self.mthread.start)

        lay = QtGui.QVBoxLayout(widget)
        lay.addWidget(self.label)

    def fun(self, s):
        self.label.setStyleSheet(warningStyle.format(100))
        self.label.setText(s)

    def displayTime(self):
        text = QtCore.QDateTime.currentDateTime().toString("dd.MM.yyyy \n HH:mm:ss")
        self.lbl.setText(_fromUtf8(text))
        self.lbl.adjustSize()
        self.adjustLabel()

    def adjustLabel(self):
        p = self.lbl.parent().rect().bottomRight() - self.lbl.rect().bottomRight()
        self.lbl.move(p)

    def resizeEvent(self, event):
        QtGui.QMainWindow.resizeEvent(self, event)
        self.adjustLabel()

class QMyThread(QtCore.QThread):
    log = QtCore.pyqtSignal(QtCore.QString)
    def run(self):
        i=0
        while True:
            i+= 1
            if i==10:
                self.setLog("Hello from thread")
                time.sleep(0.3)
                break

    def setLog(self,text):
        self.log.emit(QtCore.QString(text))

def init():
    app = QtGui.QApplication(sys.argv)
    w = MainWindow()
    w.show()
    return app, w

Upvotes: 2

Related Questions