Get current datetime in QDateTimeEdit - python

This is my first time using Qt Designer, I create function to get datetime data and then store as string in textedit
import sys
from PyQt5.QtWidgets import QMainWindow, QApplication
from PyQt5.QtCore import *
from PyQt5 import uic
Ui_MainWindow, QtBaseClass = uic.loadUiType("datetime2.ui")
class MyApp(QMainWindow):
def __init__(self):
super(MyApp,self).__init__()
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
self.ui.pushButton.clicked.connect(self.GetDatetime)
def GetDatetime(self):
dt = self.ui.dateTimeEdit.dateTime()
dt_string = dt.toString(self.ui.dateTimeEdit.displayFormat())
self.ui.textEdit.setText(dt_string)
if __name__ == "__main__":
if not QApplication.instance():
app = QApplication(sys.argv)
else:
app = QApplication.instance()
window = MyApp()
window.show()
app.exec()
Here the output
When I change dateTimeEdit column and press button the button, the value in edit text also change.
My question is, how to set datetime with local time every open the program ?
And my second question how to show the second's time, because when I ran the program, can't shown second's value ?

You have to have the current time using QDateTime.currentDateTime() and set it in the QDateTimeEdit using the setDateTime() method.
To show the seconds you must set a displayFormat that shows the seconds, for example: dd/MM/yyyy hh:mm:ss.
import sys
from PyQt5 import QtCore, QtWidgets, uic
Ui_MainWindow, QtBaseClass = uic.loadUiType("datetime2.ui")
class MyApp(QtWidgets.QMainWindow):
def __init__(self):
super(MyApp, self).__init__()
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
self.ui.pushButton.clicked.connect(self.GetDatetime)
self.ui.dateTimeEdit.setDateTime(QtCore.QDateTime.currentDateTime())
self.ui.dateTimeEdit.setDisplayFormat("dd/MM/yyyy hh:mm:ss")
def GetDatetime(self):
dt = self.ui.dateTimeEdit.dateTime()
dt_string = dt.toString(self.ui.dateTimeEdit.displayFormat())
self.ui.textEdit.setText(dt_string)
if __name__ == "__main__":
app = QtWidgets.QApplication.instance()
if app is None:
app = QtWidgets.QApplication(sys.argv)
window = MyApp()
window.show()
sys.exit(app.exec())

Related

How to make every paragraph in plaintextedit have indent in Pyside6?

I want every paragraph in plainTextEdit.text has text-indent.
I tried to use setTextIndent(). But it didn't work.
This is my code
from ui2 import Ui_Form
from PySide6.QtWidgets import QApplication,QWidget
from PySide6 import QtCore,QtGui
from PySide6.QtGui import QTextCursor
class MainWindow(QWidget):
def __init__(self):
super().__init__()
self.ui = Ui_Form()
self.ui.setupUi(self)
self.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint)
doc=self.ui.plainTextEdit.document()
a=doc.firstBlock().blockFormat()
a.setTextIndent(100)
cursor = QTextCursor(doc)
cursor.setBlockFormat(a)
cursor.insertText("This is the first paragraph\nThis is the second paragraph")
print(self.ui.plainTextEdit.document().toPlainText())
app = QApplication([])
mainw = MainWindow()
mainw.show()
app.exec()
This is my print:
This is the first paragraph
This is the second paragraph
which don't have textindent.
You have to use QTextEdit:
from PySide6.QtWidgets import QApplication, QTextEdit
from PySide6.QtGui import QTextCursor
app = QApplication([])
te = QTextEdit()
te.resize(640, 480)
te.show()
cursor = QTextCursor(te.document())
block_format = cursor.blockFormat()
block_format.setTextIndent(100)
cursor.setBlockFormat(block_format)
cursor.insertText("This is the first paragraph\nThis is the second paragraph")
app.exec()

SetText in Pyqt5

I am developing an application in pyqt5 and I ran into one problem.
There is a script that receives data, and in pyqt5 in the line "main_text.setText (str (TEXT))" I output them, and in the format "str" ​ But the script itself receives and outputs data every 0.2s, but in the line "main_text.setText (str (TEXT))" they are not updated.
Tried through the time sleep function, the app doesn't work,
what method in pyqt5 can be used to output different data to the same set text ?
My code :
from PyQt5 import QtWidgets
from PyQt5.QtWidgets import QApplication, QMainWindow
import sys
import MetaTrader5 as mt5
import time
mt5.initialize()
ticket_info = mt5.symbol_info_tick("EURUSD")._asdict()
bid_usd = mt5.symbol_info_tick("EURUSD").bid
def applecation():
app = QApplication(sys.argv)
window = QMainWindow()
window.setWindowTitle('Test Programm')
window.setGeometry(300, 250, 350, 200)
main_text = QtWidgets.QLabel(window)
main_text.setText(str(bid_usd))
main_text.move(100,100)
main_text.adjustSize()
window.show()
sys.exit(app.exec_())
if __name__ == "__main__":
applecation()
You are invoking the symbol_info_tick method only once so you will only get a data, if you want to get that information every T seconds then you must use a while True that is executed in a secondary thread so that it does not block the GUI and send the information through of signals.
import sys
import threading
import time
from PyQt5.QtCore import QObject, pyqtSignal
from PyQt5.QtWidgets import QApplication, QLabel, QMainWindow
import MetaTrader5 as mt5
class MetaTrader5Worker(QObject):
dataChanged = pyqtSignal(str)
def start(self):
threading.Thread(target=self._execute, daemon=True).start()
def _execute(self):
mt5.initialize()
while True:
bid_usd = mt5.symbol_info_tick("EURUSD").bid
self.dataChanged.emit(str(bid_usd))
time.sleep(0.5)
class MainWindow(QMainWindow):
def __init__(self, parent=None):
super().__init__(parent)
self.label = QLabel(self)
self.setWindowTitle("Test Programm")
self.setGeometry(300, 250, 350, 200)
def handle_data_changed(self, text):
self.label.setText(text)
self.label.adjustSize()
def main():
app = QApplication(sys.argv)
window = MainWindow()
window.show()
worker = MetaTrader5Worker()
worker.dataChanged.connect(window.handle_data_changed)
worker.start()
sys.exit(app.exec_())
if __name__ == "__main__":
main()
You can use threading , it's easier to understand than QThreads
from PyQt5 import QtWidgets
from PyQt5.QtWidgets import QApplication, QMainWindow
import threading
import sys
import MetaTrader5 as mt5
import time
mt5.initialize()
ticket_info = mt5.symbol_info_tick("EURUSD")._asdict()
bid_usd = mt5.symbol_info_tick("EURUSD").bid
def applecation():
app = QApplication(sys.argv)
window = QMainWindow()
window.setWindowTitle('Test Programm')
window.setGeometry(300, 250, 350, 200)
main_text = QtWidgets.QLabel(window)
main_text.move(100,100)
main_text.adjustSize()
def update_text():
while True:
main_text.setText(str(bid_usd))
time.sleep(0.2)
t1 = threading.Thread(target = update_text())
t1.start()
window.show()
sys.exit(app.exec_())
if __name__ == "__main__":
applecation()

Python Pyqt5 QDateEdit Get Date String

I'm trying to build a date printer using Pyqt5 QDateEdit. I can popup the calendar, but I want to write the clicked date's string in the console (or in a label in window). I tried print(self.calendarWidget().document().toPlainText()) or print(self.calendarWidget().currentText()) but it didn't work.
I use this code;
from PyQt5 import QtCore, QtWidgets
class DateEdit(QtWidgets.QDateEdit):
popupSignal = QtCore.pyqtSignal()
def __init__(self, parent=None):
super(DateEdit, self).__init__(parent)
self.setCalendarPopup(True)
self.calendarWidget().installEventFilter(self)
def eventFilter(self, obj, event):
if self.calendarWidget() is obj and event.type() == QtCore.QEvent.Show:
self.popupSignal.emit()
return super(DateEdit, self).eventFilter(obj, event)
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
w = DateEdit()
w.popupSignal.connect(lambda: print("popup"))
w.show()
sys.exit(app.exec_())
What is its syntax? I didn't find enough documentation for it. Can you help please?
EDIT: The answer
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtGui import QPixmap
from PyQt5.QtWidgets import *
class MyWindow(QtWidgets.QWidget):
def __init__(self, parent=None):
super(MyWindow, self).__init__(parent)
self.dateEdit = QDateEdit(self)
self.lbl = QLabel()
self.dateEdit.setMaximumDate(QtCore.QDate(7999, 12, 28))
self.dateEdit.setMaximumTime(QtCore.QTime(23, 59, 59))
self.dateEdit.setCalendarPopup(True)
layout = QGridLayout()
layout.addWidget(self.dateEdit)
layout.addWidget(self.lbl)
self.setLayout(layout)
self.dateEdit.dateChanged.connect(self.onDateChanged)
def onDateChanged(self, qDate):
print('{0}/{1}/{2}'.format(qDate.day(), qDate.month(), qDate.year()))
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
app.setApplicationName('MyWindow')
main = MyWindow()
main.show()
sys.exit(app.exec_())

Put a QToolBar in a QWidget instead of QMainWindow

I am trying to put a QToolBar on a layout of a QWidget instead of QMainWindow. On QMainWindow and QWidget is working fine, but when i try to add it on a layout first, is not. Am I doing something wrong? Is it possible? Here is my code:
from PyQt4 import QtGui, QtCore
import sys
img = '../../Images/logo.png'
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
mainWin = QtGui.QMainWindow()
widget = QtGui.QWidget()
hLayout = QtGui.QHBoxLayout()
'''ToolBar On main Window '''
basicToolBar = mainWin.addToolBar('Basic')
basicToolBar.addAction(QtGui.QAction('Test', mainWin))
# basicToolBar.addAction(QtGui.QAction(QtGui.QIcon(img), 'Test', mainWin))
# mainWin.show()
'''ToolBar On Widget '''
# Case 1: Set widget as parent
# widgetToolBar = QtGui.QToolBar(widget)
# widgetToolBar.addAction(QtGui.QAction('Test', widget))
# widgetToolBar.addAction(QtGui.QAction(QtGui.QIcon(img), QtGui.QAction('Test', widget))
# Case 2: Set toolBat on a layout
widgetToolBar = QtGui.QToolBar()
widgetToolBar.addAction(QtGui.QAction('Test', None))
# widgetToolBar.addAction(QtGui.QAction(QtGui.QIcon(img), 'Test', None))
hLayout.addWidget(widgetToolBar)
widget.setLayout(hLayout)
widget.show()
# Run
sys.exit(app.exec_())
QToolBar can only be in a QMainWindow since the QMainWindow has a special layout.
So you can use a secondary QMainWindow without problems as I show below:
from PyQt4 import QtCore, QtGui
class MainWindow(QtGui.QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.tabwidget = QtGui.QTabWidget()
self.setCentralWidget(self.tabwidget)
for name in ("tab1", "tab2", "tab3"):
self.create_widgets(name)
def create_widgets(self, name):
w = QtGui.QMainWindow()
self.tabwidget.addTab(w, name)
basicToolBar = w.addToolBar('Basic')
basicToolBar.addAction('Test')
basicToolBar.addAction(QtGui.QIcon("home.png"), 'Test')
tab = QtGui.QTabWidget()
w.setCentralWidget(tab)
for i in range(10):
tab.addTab(QtGui.QWidget(), "tab-{}".format(i))
if __name__ == '__main__':
import sys
app = QtGui.QApplication(sys.argv)
w = MainWindow()
w.show()
sys.exit(app.exec_())
Hmmm have you read the description of QToolBar? http://doc.qt.io/qt-5/qtoolbar.html#details
I think it won't work like this if your Object isn't a child of QMainWindow. The documentation says:
When a QToolBar is not a child of a QMainWindow, it loses the ability to populate the extension pop up with widgets added to the toolbar using addWidget(). Please use widget actions created by inheriting QWidgetAction and implementing QWidgetAction::createWidget() instead.

Qt Multiple GraphicsEffects

Is there a way in Qt5 to apply a QGraphicsEffect to a widget, even when one of its parent widgets already has a QGraphicsEffect applied to it?
When i try the following:
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
import sys
class ParentWidget(QWidget):
def __init__(self,parent):
super().__init__(parent)
effect = QGraphicsBlurEffect(self)
self.setGraphicsEffect(effect)
effect.setBlurRadius(0)
class ChildWidget(ParentWidget):
def __init__(self,parent):
super().__init__(parent)
self.layout = QGridLayout(self)
widget = QWidget()
widget.setObjectName('reviewControlArea')
effect = QGraphicsOpacityEffect(widget)
widget.setGraphicsEffect(effect)
self.layout.addWidget(widget)
if __name__ == "__main__":
app = QApplication(sys.argv)
MainWindow = QMainWindow()
cw = ChildWidget(MainWindow)
MainWindow.setCentralWidget(cw)
MainWindow.show()
sys.exit(app.exec_())
The stdout says:
QPainter::begin: A paint device can only be painted by one painter at a time.

Categories