pyqt5 / qtdesigner textbox default label - python

I am trying to create a GUI for my python program. One of the tools that I need is a text input box.
Now, I want a text label for this box saying "Please insert texts." Is there a function to add a label that shows inside the input textbox as default and disappear when user click the box to type?
I don't mind to use qt designer or pyqt5 coding.
Thank you guys.

placeholderText : QString
This property holds the line edit's placeholder text
import sys
from PyQt5.QtWidgets import QLineEdit, QVBoxLayout, QApplication, QWidget
class Test(QWidget):
def __init__(self):
super().__init__()
self.lineEdit = QLineEdit(placeholderText="Please insert texts.") # <---
vbox = QVBoxLayout(self)
vbox.addWidget(self.lineEdit)
if __name__ == '__main__':
app = QApplication(sys.argv)
w = Test()
w.show()
sys.exit(app.exec_())

I am begginer like you and my English is not so good. But I recommend you use Qt Designer. It's easier, fastter for you draw your app. I am using pyside2 project and recommend you read docummentatio each widgets you wanna use in PySide2 project and Qt Project. Try code below
enter image description here
import sys
from PySide2.QtWidgets import QApplication
from PySide2.QtWidgets import QDialog
from PySide2.QtWidgets import QTextEdit
from PySide2.QtWidgets import QVBoxLayout
from PySide2.QtCore import Qt
class MainDialog(QDialog):
def __init__(self, parent=None):
super(MainDialog, self).__init__(parent)
# Create Widget TextEdit
self.text = QTextEdit()
# I think that you wanna this function in your program
# https://doc.qt.io/qtforpython/PySide2/QtWidgets/QLineEdit.html?highlight=qlineedit#PySide2.QtWidgets.PySide2.QtWidgets.QLineEdit.setPlaceholderText
# http://doc.qt.io/qt-5/qlineedit.html#placeholderText-prop
self.text.setPlaceholderText('''Yes! this is exactly what I want!
Thank you, what if you have a big text box (more than 10 lines) and
you want to scale up the place holder and align it in center?? ''')
# https://doc.qt.io/qtforpython/PySide2/QtWidgets/QLineEdit.html?highlight=qlineedit#PySide2.QtWidgets.PySide2.QtWidgets.QLineEdit.setAlignment
# http://doc.qt.io/qt-5/qlineedit.html#alignment-prop
self.text.setAlignment(Qt.AlignCenter)
# Layout
layout = QVBoxLayout()
layout.addWidget(self.text)
self.setLayout(layout)
def main():
app = QApplication()
mainDialog = MainDialog()
mainDialog.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()

Related

Adding a leaflet map to PyQt5

I am new to Qt and PyQt and I appreciate it if someone can help me with this. I am trying to add a leaflet map to a GUI that I am creating using Qt designer and Python. Since there is no such widget, I create a simple Widget in the Qt Designer and promote it to a "LeafWidget" as shown below:
I save this file as (user_interface.ui) and then in my index.py file (under the same folder), I use the class leafWidget (with the same name as what defined in the Qt Designer) to define this new widget. I'm not sure if it is right or not. My "index.py" file that I run is as below.
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from pyqtlet import L, MapWidget
from PyQt5.uic import loadUiType
ui,_=loadUiType('user_interface.ui')
class LeafWidget (QWidget):
def __init__(self):
QWidget.__init__(self)
self.mapWidget = MapWidget()
self.map = L.map(self.mapWidget)
self.map.setView([39.764075, -86.159019], 10)
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png').addTo(self.map)
self.layout = QVBoxLayout(self)
self.layout.addWidget(self.mapWidget)
self.show()
class MainApp(QMainWindow, ui):
def __init__(self):
QMainWindow.__init__(self)
self.setupUi(self)
self.mainWindow_tabWidget.setCurrentIndex(1)
def main():
app=QApplication(sys.argv)
window = MainApp()
window.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
When I run it, it does open up the window, but the place for the map widget is empty as you see below. Am I defining this class correctly? In my MainApp class, do I need to add this new custom widget somehow? I don't get any specific errors in my debug console, So I'm not sure what I am missing.

How application structure should looks like?

I'm trying to create a small database app to keep all clients inside. I would like to write GUI using PyQt5. I have a problem with understanding how app structure should looks like.
I'd like to have a main class which starts the app and I want to seperate GUI, DB and Main classes in different files.
You can see my code snippets bellow. It don't work because some variables are not recognized and accually I don't understand why.
My thoughts:
1. Window, tab1 objects will be created in main class init function
2. When window, tab1 instances were created, the methods inside it's init will be called
3. I have window, tab1 objects and it's variables are available for themselves
window.gbT1Main.setLayout(T1LayMain) is not defined for TabNewClient class. Why ? How should I change my code to achieve above requirements? Please explain me how should I connect my classes :(
Window and TabNewClient class (window, tab1)
from PyQt5.QtWidgets import QApplication, QDialog, QTabWidget, QGroupBox, QVBoxLayout, QHBoxLayout, QLabel, QPushButton, QFormLayout, QLineEdit, QDateEdit, QTextEdit, QRadioButton, QGridLayout
import sys
import datetime
class Window(QDialog):
def __init__(self):
super().__init__()
self.InitWindow()
def InitWindow(self):
# create tab widget
self.tab = QTabWidget()
# create MainWindow groupbox
self.gbMainWindow = QGroupBox()
# TAB groupBoxes
self.gbT1Main = QGroupBox()
self.gbT2Main = QGroupBox("Main2")
self.gbT3Main = QGroupBox("Main3")
# Adding tabs
self.tab.addTab(self.gbT1Main, "Dodaj klienta")
self.tab.addTab(self.gbT2Main, "Wyszukaj")
self.tab.addTab(self.gbT3Main, "Statystki")
# Setting MainWindow title
self.setWindowTitle("MEDIKAP - gabinet medycyny pracy")
# Main Window Layout
self.layMainWindow = QHBoxLayout()
# Set MainWindow Layout
self.layMainWindow.addWidget(self.tab)
self.gbMainWindow.setLayout(self.layMainWindow)
# set MainWindow layout visible
self.setLayout(self.layMainWindow)
#show window
self.show()
class TabNewClient:
def __init__(self):
self.CreateTab1Layout()
def CreateTab1Layout(self):
self.gbAddClient = QGroupBox("Dane klienta")
self.gbRodzajBadania = QGroupBox("Podstawa prawna")
self.gbDane = QGroupBox()
self.gbComment = QGroupBox("Komentarz")
self.gbButtons = QGroupBox()
# TAB1 - layouts
T1LayMain = QVBoxLayout()
layDane = QHBoxLayout()
# TAB1
layDane.addWidget(self.gbAddClient)
layDane.addWidget(self.gbRodzajBadania)
self.gbDane.setLayout(layDane)
# TAB1 - set layout to Main
T1LayMain.addWidget(self.gbDane)
T1LayMain.addWidget(self.gbComment)
T1LayMain.addWidget(self.gbButtons)
window.gbT1Main.setLayout(T1LayMain)
Main class:
from PyQt5.QtWidgets import QApplication
import sys
from guiv3 import Window, TabNewClient
class Main:
def __init__(self):
window = Window()
tab1 = TabNewClient()
if __name__ == "__main__":
app = QApplication(sys.argv)
main = Main()
app.exec_()
error:
window.gbT1Main.setLayout(T1LayMain)
NameError: name 'window' is not defined
To answer the question of why you get an error about 'window' not being defined, I believe it's because there is no window variable in the TabNewClient class. It looks like you're attempting to refer to the window defined in Main, but that won't work since that variable isn't in the scope of the TabNewClient class. My guess is that you're going to run into the same issue with gbT1Main, since that is outside the scope of the TabNewClient class as well.
Edit: I think I understand what you're attempting here. You want the gbT1Main related tab in window to hold the layout from tab1. To do that, you will need to set window's layout in Main:
from PyQt5.QtWidgets import QApplication
import sys
from guiv3 import Window, TabNewClient
class Main:
def __init__(self):
window = Window()
tab1 = TabNewClient()
window.gbT1Main.setLayout(tab1.T1LayMain)
if __name__ == "__main__":
app = QApplication(sys.argv)
main = Main()
app.exec_()
That's most likely what you're looking for.
Important: this also requires that T1LayMain be an attribute of the TabNewClient class, so use self.T1LayMain inside that class for it to be accessible outside it.

How to remove the divider between widgets when using `statusBar.addPermanentWidget()`?

Is it possible to remove the divider line between two widgets that were added to the status bar using .addPermanentWidget()? I suspect that it is possible, but I haven't really found any literature on how to proceed.
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QStatusBar, QLabel
class MainWindow(QMainWindow):
def __init__(self):
QMainWindow.__init__(self)
statusBar = QStatusBar()
self.setStatusBar(statusBar)
statusBar.addPermanentWidget(QLabel("Label: "))
statusBar.addPermanentWidget(QLabel("Data"))
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
In order to remove the divider between the two elements you need to set the stylesheet for QStatusBar::item in either Qt Creator, or the project source.
Qt Creator Example:
Project Source Example:
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QStatusBar, QLabel
class MainWindow(QMainWindow):
def __init__(self):
QMainWindow.__init__(self)
statusBar = QStatusBar()
statusBar.setStyleSheet('QStatusBar::item {border: None;}')
self.setStatusBar(statusBar)
statusBar.addPermanentWidget(QLabel("Label: "))
statusBar.addPermanentWidget(QLabel("Data"))
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
Another way is to combine several widgets into one to group them, something like the C++ below:
QWidget *widget = new QWidget;
QLayout* layout = new QHBoxLayout(widget);
layout->setMargin(0);
QLabel *label = new QLabel;
label->setText("Recording status");
layout->addWidget(label);
QLabel *m_RecordingStatus = new QLabel;
m_RecordingStatus->setFrameShape(QFrame::Shape::Box);
m_RecordingStatus->setFixedWidth(100);
layout->addWidget(m_RecordingStatus);
ui.m_statusBar->addPermanentWidget(widget);
You can group associated widgets to be together between dividers.

Image not displaying after move from PySide to PyQt5

I went from PySide to PyQt5 because I want to use some older code I have written and Python 3.5 does not support PySide anymore and PySide2 or Python 3.4 does not work for me either.
The last line in the code below used to get me the Example.JPG displayed. Now it does not seem to do anything for me with PyQt5
self.scene = QtWidgets.QGraphicsScene()
self.view = QtWidgets.QGraphicsView(self.scene)
layout.addWidget(self.view, 1, 0, 1, 0)
self.view.scale(0.15,0.15)
self.view.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.view.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.view.setTransformationAnchor(self.view.AnchorUnderMouse)
self.view.wheelEvent = self.scrollSelect
self.view.keyPressEvent = self.keypressed
self.fpimage = 'Example.JPG'
self.pixmap_item = QtWidgets.QGraphicsPixmapItem(QtGui.QPixmap(self.fpimage), None, self.scene)
Giving a complete working set of code is a bit difficult since I can't use PySide anymore to confirm.
Is there a way to get the image show up again?
I found the solution, in stead of this (worked with PySide):
self.pixmap_item = QtWidgets.QGraphicsPixmapItem(QtGui.QPixmap(self.fpimage), None, self.scene)
i now have:
self.pixmap_item = QtWidgets.QGraphicsPixmapItem(QtGui.QPixmap(self.fpimage))
self.scene.addItem(self.pixmap_item)
And it is displaying the picture in my QGraphicsScene with PyQt5.
In your case you're missing below codelines for showing a picture in a label:
pixmap = QtGui.QPixmap(self.mainwindow_image).scaled(main_width, main_height, aspectRatioMode = 1)
self.label = QtWidgets.QLabel(self.widget_1)
self.label.setMinimumSize(QtCore.QSize(225, 200))
self.label.setMaximumSize(QtCore.QSize(225, 200))
self.label.setText("")
self.label.setObjectName("label")
self.label.setPixmap(pixmap)
As your code is incomplete I've added you an example from the Qt designer Mark Summers calculate (updated pyqt5 style) to learn from (read: skeleton structure of apyqt5 gui) and apply the above label code. Enjoy.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys, os
from math import *
from PyQt5 import *
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QAction, QApplication, QDialog, QLineEdit, QTextBrowser, QVBoxLayout, QWidget
#from PyQt5.QtGui import
class Form(QDialog):
def __init__(self, parent = None):
super(Form, self).__init__(parent)
self.browser = QTextBrowser()
self.lineedit = QLineEdit("Lots of text here... type something and press Enter")
self.lineedit.selectAll()
layout = QVBoxLayout()
layout.addWidget(self.browser)
layout.addWidget(self.lineedit)
# starts at the lineEdit for the user to type straight away.
self.setLayout(layout)
self.lineedit.setFocus()
self.lineedit.returnPressed.connect(self.updateUi)
self.setWindowTitle("Calculate the shit out of your CPU")
def updateUi(self):
try:
text = unicode(self.lineedit.text())
self.browser.append("%s = <b>%s<b/>" % (text, eval(text)))
except:
self.browser.append("<font color=red> %s is invalid!</font>" % text)
pass
if __name__ == '__main__':
app = QApplication(sys.argv)
window = Form()
window.show()
sys.exit(app.exec_())

change text of lineEdit when a radio button is selected in pyqt

I have two radioButtons in the form made using qt designer, i am now programming in pyqt. i wish to change the text of lineEdit to "radio 1" when radioButton 1 is selected and "radio 2" when the radioButton 2 is selected. how can I achieve this?
Here's a simple example. Each QRadioButton is connected to it's own function. You could connect them both to the same function and manage what happens through that, but I thought best to demonstrate how the signals and slots work.
For more info, take a look at the PyQt4 documentation for new style signals and slots. If connecting multiple signals to the same slot it's sometimes useful to use the .sender() method of a QObject, although in the case of QRadioButton it's probably easier to just check the .isChecked() method of your desired buttons.
import sys
from PyQt4.QtGui import QApplication, QWidget, QVBoxLayout, \
QLineEdit, QRadioButton
class Widget(QWidget):
def __init__(self, parent=None):
QWidget.__init__(self, parent)
self.widget_layout = QVBoxLayout()
self.radio1 = QRadioButton('Radio 1')
self.radio2 = QRadioButton('Radio 2')
self.line_edit = QLineEdit()
self.radio1.toggled.connect(self.radio1_clicked)
self.radio2.toggled.connect(self.radio2_clicked)
self.widget_layout.addWidget(self.radio1)
self.widget_layout.addWidget(self.radio2)
self.widget_layout.addWidget(self.line_edit)
self.setLayout(self.widget_layout)
def radio1_clicked(self, enabled):
if enabled:
self.line_edit.setText('Radio 1')
def radio2_clicked(self, enabled):
if enabled:
self.line_edit.setText('Radio 2')
if __name__ == '__main__':
app = QApplication(sys.argv)
widget = Widget()
widget.show()
sys.exit(app.exec_())

Categories