I am writing this program to auto save data to Postgres database when QT Text Edit detects the length of string is greater than 5 characters. The program also displaying current date and time.
note: I had created a save button for save the data in QT Text Edit. But actually I need the data to be saved once the QT Text Edit detects the length is more than 5 characters.
I am facing the difficulties as below:
The time displayed is stop, it is called and show when the apps is launched but after that it is just showing static.
the " if len(self.barcode_in) >= 5: " in line 106 is having error.
I did research on Python schedule, but seems like the minimum interval for scanning is 0.5 seconds. Do I need to use threading function to refresh the clock displayed and scan the length of QT Text Edit?
My full code is as below.
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'savebarcodedatetime.ui'
#
# Created by: PyQt5 UI code generator 5.13.0
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import QTime, QTimer
from PyQt5.QtCore import QDate, Qt
from PyQt5.QtWidgets import QApplication, QLCDNumber
import threading
import psycopg2
#from config import config
from threading import Thread
from datetime import *
import time
from time import time
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(800, 600)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.widget = QtWidgets.QWidget(self.centralwidget)
self.widget.setGeometry(QtCore.QRect(50, 10, 721, 531))
self.widget.setObjectName("widget")
self.verticalLayout_2 = QtWidgets.QVBoxLayout(self.widget)
self.verticalLayout_2.setContentsMargins(0, 0, 0, 0)
self.verticalLayout_2.setObjectName("verticalLayout_2")
self.horizontalLayout = QtWidgets.QHBoxLayout()
self.horizontalLayout.setObjectName("horizontalLayout")
spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Minimum)
self.horizontalLayout.addItem(spacerItem)
self.show_time = QtWidgets.QLCDNumber(self.widget) #LCD = show_time
font = QtGui.QFont()
font.setPointSize(16)
self.show_time.setFont(font)
self.show_time.setObjectName("show_time")
self.horizontalLayout.addWidget(self.show_time)
spacerItem1 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
self.horizontalLayout.addItem(spacerItem1)
self.show_date = QtWidgets.QLabel(self.widget)
font = QtGui.QFont()
font.setPointSize(16)
self.show_date.setFont(font)
self.show_date.setObjectName("show_date")
self.horizontalLayout.addWidget(self.show_date)
spacerItem2 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Minimum)
self.horizontalLayout.addItem(spacerItem2)
self.verticalLayout_2.addLayout(self.horizontalLayout)
spacerItem3 = QtWidgets.QSpacerItem(20, 40, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)
self.verticalLayout_2.addItem(spacerItem3)
self.tableWidget = QtWidgets.QTableWidget(self.widget)
self.tableWidget.setObjectName("tableWidget")
self.tableWidget.setColumnCount(0)
self.tableWidget.setRowCount(0)
self.verticalLayout_2.addWidget(self.tableWidget)
spacerItem4 = QtWidgets.QSpacerItem(20, 40, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)
self.verticalLayout_2.addItem(spacerItem4)
self.verticalLayout = QtWidgets.QVBoxLayout()
self.verticalLayout.setObjectName("verticalLayout")
self.barcode_in = QtWidgets.QTextEdit(self.widget)
self.barcode_in.setObjectName("barcode_in")
self.verticalLayout.addWidget(self.barcode_in)
spacerItem5 = QtWidgets.QSpacerItem(20, 20, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Preferred)
self.verticalLayout.addItem(spacerItem5)
self.save_button = QtWidgets.QPushButton(self.widget)
font = QtGui.QFont()
font.setPointSize(24)
self.save_button.setFont(font)
self.save_button.setObjectName("save_button")
self.verticalLayout.addWidget(self.save_button)
spacerItem6 = QtWidgets.QSpacerItem(20, 20, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Preferred)
self.verticalLayout.addItem(spacerItem6)
self.verticalLayout_2.addLayout(self.verticalLayout)
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 21))
self.menubar.setObjectName("menubar")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
self.save_button.clicked.connect(self.save_db)
printoutput.printoutmessage()
todaydate = QTime.currentTime()
print(todaydate.toString(Qt.DefaultLocaleLongDate))
todaydate_str = todaydate.toString("H:mm:ss")
self.show_date.setText(todaydate_str)
print(todaydate.toString(Qt.DefaultLocaleLongDate))
if len(self.barcode_in) >= 5:
barcodedata = self.barcode_in.toPlainText()
insertdb.insert_vendor(barcodedata)
print('barcode save')
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.show_date.setText(_translate("MainWindow", "TextLabel"))
self.save_button.setText(_translate("MainWindow", "Save"))
def save_db(self):
print("save")
#mytext = self.textEdit.toPlainText()
barcodedata = self.barcode_in.toPlainText()
insertdb.insert_vendor(barcodedata)
#barcode_in = ''
today = datetime.now()
print (today.strftime(' %a %d-%m-%Y # %H:%M:%S'))
class insertdb:
def insert_vendor(vendor_name):
""" insert a new vendor into the vendors table """
sql = """INSERT INTO vendors(vendor_name)
VALUES(%s) RETURNING vendor_id;"""
conn = None
vendor_id = None
try:
conn = psycopg2.connect(host="192.168.1.104",
port = 5432, database="suppliers",
user="pi", password="1234")
cur = conn.cursor()
# execute the INSERT statement
cur.execute(sql, (vendor_name,))
# get the generated id back
vendor_id = cur.fetchone()[0]
conn.commit()
cur.close()
except (Exception, psycopg2.DatabaseError) as error:
print(error)
finally:
if conn is not None:
conn.close()
return vendor_id
class printoutput:
def printoutmessage():
print("print output")
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
qtextedit can emit signals every time the text on it changes, here is the name and doc.
My suggestion is to connect that signal to you self-defined slot and in the implementation of that method check the length of the new text... is more efficient than polling every "x" seconds for the size of a string.
Now, to the error here:
if len(self.barcode_in) >= 5:
is not valid since
self.barcode_in is actually a widget, you initialized it like doing
self.barcode_in = QtWidgets.QTextEdit(self.widget) therfore makes no sense to compare it against a number, but what you want is to compare the len of the text in that widget, and for this you need the "plain-text" of it (here the doc for that)
Related
I'm making a GUI with PyQt5.
I'm very very new to it. I need help.
First i have a stacked widget that I can use to switch between pages.
Right now im trying to make a setings page.
Settings Page
I know that putting stacked widgets for changing like "window"/page in pyqt5 might not be the best but ignore if you want to (if its bad give me a suggestion please).
Right now I want to check if the Dark Mode checkbox is enabled.
I have a MainWindow.py and I have a gui.py which is the one that I transformed from a .ui to .py (pyuic5 cmd).
In MainWindow.py I'm handling all of the gui's "commands/buttons".
gui.py is the file with all of the gui imported from qt designer.
I also have settings.config which is the files where I try to save the settings.
BTW my main idea was to write when the check box was clicked to save the thing to the .config file (which it does) and then check from MainWindow.py if the text == 'Dark Mode: True'
The Big Question How do I make it so the checkbox can be checked from another file (MainWindow.py)?
Also, if not should I change how the gui is handled and stuff.
Heres my code BTW:
The MainWindow.py Script:
import sys
import PyQt5
from PyQt5.QtWidgets import QApplication
from PyQt5.QtWidgets import QMainWindow
from gui import Ui_MainWindow
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import *
class MainWindow:
def __init__(self):
self.main_win = QMainWindow()
self.ui = Ui_MainWindow()
self.ui.setupUi(self.main_win)
self.main_win.setWindowTitle("GUI App")
self.ui.stackedWidget.setCurrentWidget(self.ui.start)
# Start Screen
self.ui.startButton.clicked.connect(self.showHomeScreen)
self.ui.settingsButton.clicked.connect(self.showSettingsScreen)
# Settings Screen
self.ui.backStartButton.clicked.connect(self.showStartScreen)
self.ui.darkModeEnabled.clicked.connect(self.checkDarkMode)
# Home Screen
self.ui.backToStartHome.clicked.connect(self.showStartScreen)
def showHomeScreen(self):
self.ui.stackedWidget.setCurrentWidget(self.ui.home)
# Start Screen Funcions
def showStartScreen(self):
self.ui.stackedWidget.setCurrentWidget(self.ui.start)
# Settings Functions
def showSettingsScreen(self):
self.ui.stackedWidget.setCurrentWidget(self.ui.settings)
def checkDarkMode(self):
if self.ui.darkModeEnabled.isChecked() == True:
self.f = open('settings.config', 'w')
self.f.write("Darkmode: True")
self.f.close()
if self.ui.darkModeEnabled.isChecked() == False:
self.f = open('settings.config', 'w')
self.f.write("Darkmode: False")
self.f.close()
for line in open('settings.config', 'r'):
if line == 'Darkmode: True':
self.ui.darkModeEnabled.setChecked(True)
print('Darkmode is on!')
elif line == 'Darkmode: False':
self.ui.darkModeEnabled.setChecked(False)
print('Darkmode is off!')
def show(self):
self.main_win.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
main_win = MainWindow()
main_win.show()
sys.exit(app.exec_())
The gui.py script:
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(597, 319)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.stackedWidget = QtWidgets.QStackedWidget(self.centralwidget)
self.stackedWidget.setGeometry(QtCore.QRect(-21, -11, 651, 321))
self.stackedWidget.setObjectName("stackedWidget")
self.start = QtWidgets.QWidget()
self.start.setObjectName("start")
self.label = QtWidgets.QLabel(self.start)
self.label.setGeometry(QtCore.QRect(130, 30, 351, 81))
font = QtGui.QFont()
font.setFamily("MS Gothic")
font.setPointSize(48)
self.label.setFont(font)
self.label.setAlignment(QtCore.Qt.AlignCenter)
self.label.setObjectName("label")
self.startButton = QtWidgets.QPushButton(self.start)
self.startButton.setGeometry(QtCore.QRect(150, 180, 131, 51))
self.startButton.setObjectName("startButton")
self.settingsButton = QtWidgets.QPushButton(self.start)
self.settingsButton.setGeometry(QtCore.QRect(310, 180, 131, 51))
self.settingsButton.setObjectName("settingsButton")
self.stackedWidget.addWidget(self.start)
self.home = QtWidgets.QWidget()
self.home.setObjectName("home")
self.label_2 = QtWidgets.QLabel(self.home)
self.label_2.setGeometry(QtCore.QRect(160, 30, 351, 81))
font = QtGui.QFont()
font.setFamily("MS Gothic")
font.setPointSize(48)
self.label_2.setFont(font)
self.label_2.setAlignment(QtCore.Qt.AlignCenter)
self.label_2.setObjectName("label_2")
self.backToStartHome = QtWidgets.QPushButton(self.home)
self.backToStartHome.setGeometry(QtCore.QRect(34, 42, 91, 51))
self.backToStartHome.setObjectName("backToStartHome")
self.stackedWidget.addWidget(self.home)
self.settings = QtWidgets.QWidget()
self.settings.setObjectName("settings")
self.label_3 = QtWidgets.QLabel(self.settings)
self.label_3.setGeometry(QtCore.QRect(130, 0, 431, 111))
font = QtGui.QFont()
font.setFamily("MS Gothic")
font.setPointSize(48)
self.label_3.setFont(font)
self.label_3.setAlignment(QtCore.Qt.AlignCenter)
self.label_3.setObjectName("label_3")
self.backStartButton = QtWidgets.QPushButton(self.settings)
self.backStartButton.setGeometry(QtCore.QRect(30, 40, 91, 31))
self.backStartButton.setObjectName("backStartButton")
self.darkModeEnabled = QtWidgets.QCheckBox(self.settings)
self.darkModeEnabled.setGeometry(QtCore.QRect(30, 130, 111, 21))
font = QtGui.QFont()
font.setFamily("MS Reference Sans Serif")
font.setPointSize(12)
self.darkModeEnabled.setFont(font)
self.darkModeEnabled.setObjectName("darkModeEnabled")
self.stackedWidget.addWidget(self.settings)
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 597, 21))
self.menubar.setObjectName("menubar")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.label.setText(_translate("MainWindow", "Start Page"))
self.startButton.setText(_translate("MainWindow", "Start"))
self.settingsButton.setText(_translate("MainWindow", "Settings"))
self.label_2.setText(_translate("MainWindow", "Home Page"))
self.backToStartHome.setText(_translate("MainWindow", "Back to Start"))
self.label_3.setText(_translate("MainWindow", "Settings Page"))
self.backStartButton.setText(_translate("MainWindow", "Back to Start"))
self.darkModeEnabled.setText(_translate("MainWindow", "Dark Mode"))
If you read all of this and know how to fix this please help.
And if you didn't but just know please help.
Thank You
I tried to design a very basic GUI app that shows the entered height on a dialog, but after I press the ‘OK’ button on the main window, the whole program crashes and the process finishes with this exit code:
Process finished with exit code -1073740791 (0xC0000409)
Here’s the full code for the app, the UI files are below:
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.uic import *
class My_Dialog(QDialog):
def __init__(self):
super(My_Dialog, self).__init__()
loadUi("dialog.ui", self)
self.mid_label.setText(My_Window.mid_label_nexttext)
class My_Window(QMainWindow):
def __init__(self):
super(My_Window, self).__init__()
loadUi("mainwindow.ui", self)
self.mid_label_nexttext = None
self.height_selecter_spinbox.textChanged.connect(lambda x: self.spin_changed(x))
self.pushButton.clicked.connect(self.onMyPushButtonClick)
def onMyPushButtonClick(self):
dlg = My_Dialog()
if dlg.exec_():
print("Success!")
else:
print("Cancel!")
def spin_changed(self, s):
self.mid_label_nexttext = s
self.update()
def main():
app = QApplication(sys.argv)
window = My_Window()
window.show()
app.exec_()
if __name__ == "__main__":
main()
The main window’s UI:
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'mainwindow.ui'
#
# Created by: PyQt5 UI code generator 5.15.0
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(513, 171)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.pushButton = QtWidgets.QPushButton(self.centralwidget)
self.pushButton.setGeometry(QtCore.QRect(310, 80, 75, 23))
self.pushButton.setObjectName("pushButton")
self.layoutWidget = QtWidgets.QWidget(self.centralwidget)
self.layoutWidget.setGeometry(QtCore.QRect(90, 40, 209, 29))
self.layoutWidget.setObjectName("layoutWidget")
self.layout = QtWidgets.QHBoxLayout(self.layoutWidget)
self.layout.setContentsMargins(0, 0, 0, 0)
self.layout.setObjectName("layout")
self.label_firstpart = QtWidgets.QLabel(self.layoutWidget)
font = QtGui.QFont()
font.setPointSize(15)
self.label_firstpart.setFont(font)
self.label_firstpart.setObjectName("label_firstpart")
self.layout.addWidget(self.label_firstpart)
self.height_selecter_spinbox = QtWidgets.QSpinBox(self.layoutWidget)
font = QtGui.QFont()
font.setPointSize(13)
self.height_selecter_spinbox.setFont(font)
self.height_selecter_spinbox.setMinimum(100)
self.height_selecter_spinbox.setMaximum(250)
self.height_selecter_spinbox.setProperty("value", 175)
self.height_selecter_spinbox.setObjectName("height_selecter_spinbox")
self.layout.addWidget(self.height_selecter_spinbox)
self.label_lastpart = QtWidgets.QLabel(self.layoutWidget)
font = QtGui.QFont()
font.setPointSize(15)
self.label_lastpart.setFont(font)
self.label_lastpart.setObjectName("label_lastpart")
self.layout.addWidget(self.label_lastpart)
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 513, 21))
self.menubar.setObjectName("menubar")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.pushButton.setText(_translate("MainWindow", "OK"))
self.label_firstpart.setText(_translate("MainWindow", "My height is "))
self.label_lastpart.setText(_translate("MainWindow", "cm."))
The dialog’s UI:
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'dialog.ui'
#
# Created by: PyQt5 UI code generator 5.15.0
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Dialog(object):
def setupUi(self, Dialog):
Dialog.setObjectName("Dialog")
Dialog.resize(400, 300)
self.dialog_buttonbox = QtWidgets.QDialogButtonBox(Dialog)
self.dialog_buttonbox.setGeometry(QtCore.QRect(30, 240, 341, 32))
self.dialog_buttonbox.setOrientation(QtCore.Qt.Horizontal)
self.dialog_buttonbox.setStandardButtons(QtWidgets.QDialogButtonBox.Cancel|QtWidgets.QDialogButtonBox.Ok)
self.dialog_buttonbox.setObjectName("dialog_buttonbox")
self.widget = QtWidgets.QWidget(Dialog)
self.widget.setGeometry(QtCore.QRect(80, 90, 151, 41))
self.widget.setObjectName("widget")
self.dialog_layout = QtWidgets.QHBoxLayout(self.widget)
self.dialog_layout.setContentsMargins(0, 0, 0, 0)
self.dialog_layout.setObjectName("dialog_layout")
self.left_label = QtWidgets.QLabel(self.widget)
font = QtGui.QFont()
font.setPointSize(12)
self.left_label.setFont(font)
self.left_label.setObjectName("left_label")
self.dialog_layout.addWidget(self.left_label)
self.mid_label = QtWidgets.QLabel(self.widget)
font = QtGui.QFont()
font.setPointSize(12)
self.mid_label.setFont(font)
self.mid_label.setObjectName("mid_label")
self.dialog_layout.addWidget(self.mid_label)
self.right_label = QtWidgets.QLabel(self.widget)
font = QtGui.QFont()
font.setPointSize(12)
self.right_label.setFont(font)
self.right_label.setObjectName("right_label")
self.dialog_layout.addWidget(self.right_label)
self.retranslateUi(Dialog)
self.dialog_buttonbox.accepted.connect(Dialog.accept)
self.dialog_buttonbox.rejected.connect(Dialog.reject)
QtCore.QMetaObject.connectSlotsByName(Dialog)
def retranslateUi(self, Dialog):
_translate = QtCore.QCoreApplication.translate
Dialog.setWindowTitle(_translate("Dialog", "Dialog"))
self.left_label.setText(_translate("Dialog", "You are"))
self.mid_label.setText(_translate("Dialog", "100"))
self.right_label.setText(_translate("Dialog", "cm tall."))
I would appreciate some help on fixing this error, and on why it occured.
You are trying to access an attribute that does not exist:
self.mid_label.setText(My_Window.mid_label_nexttext)
My_Window is a class, while mid_label_nexttext was assigned to the instance of that class (self is always the reference to the current instance).
If you want to set the text for that label from a "parent" window, you either add an extra argument to the __init__ that allows to get the text, or you set it from the main window.
Use the text as init argument
class My_Dialog(QDialog):
def __init__(self, text):
super(My_Dialog, self).__init__()
loadUi("dialog.ui", self)
# ensure that "text" is a valid string, you can't use setText(None)
if text:
self.mid_label.setText(text)
class My_Window(QMainWindow):
# ...
def onMyPushButtonClick(self):
dlg = My_Dialog(self.mid_label_nexttext)
# ...
Set the text from the parent
class My_Dialog(QDialog):
def __init__(self):
super(My_Dialog, self).__init__()
loadUi("dialog.ui", self)
# NO setText() here!!!
class My_Window(QMainWindow):
# ...
def onMyPushButtonClick(self):
dlg = My_Dialog()
if self.mid_label_nexttext:
dlg.mid_label.setText(self.mid_label_nexttext)
# ...
Note that the first method is usually better, mostly for modularity reasons: let's say that you create that dialog from different classes in different situations, whenever you need to change the object name of the label (or the whole interface structure) you can easily change its reference in the dialog subclass, otherwise you'll need to change every reference in your code.
Note: the call to self.update() is useless; if you want to update the label on the dialog whenever the spinbox value is changed, you need to directly access the label (like in the last example) or use signals. Also, you don't need to use lambda if you're using the same argument parameter, just connect to the function.
I used this code to manage a countdown using PyQt5. code -
import time
import serial
from PyQt5 import QtCore
argument = serial.Serial('COM5',9600)
countDown = 9999
def timerEvent():
global time
time = time.addSecs(-1)
global argument
global new
data = time.toString("mmss")
print(data)
argument.write(data.encode());
if data == '0000':
argument.close()
timer.stop()
global countDown
countDown = data
time.sleep(2);
app = QtCore.QCoreApplication(sys.argv)
timer = QtCore.QTimer()
time = QtCore.QTime(0, 1,0)
timer.timeout.connect(timerEvent)
timer.start(200)
But i want is i will input the minute and increment value using a GUI.But, can not implement. Any suggestions how can i implement that?
heres my GUI
I created a new self function under class Ui_Mainwindow that connects the button to implement timer. However, it always says self error. i know how to get the lineEdit values but when i want to put it in
line 38 time = QtCore.QTime(0, 1,0) it shows self error. again the line no 40 timer.timeout.connect(timerEvent) timerevent shows error.
any idea how to implement using the GUI ? Sorry for my poor explanation. is there any other way to do this?
heres the code, i just tried to do similar like base code mentioned above.
import time
countDown = 9999
from PyQt5 import QtCore, QtGui, QtWidgets
inc = 9999
newTime = 9999
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(800, 600)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.groupBox = QtWidgets.QGroupBox(self.centralwidget)
self.groupBox.setGeometry(QtCore.QRect(70, 180, 131, 121))
self.groupBox.setTitle("")
self.groupBox.setObjectName("groupBox")
self.label_2 = QtWidgets.QLabel(self.groupBox)
self.label_2.setGeometry(QtCore.QRect(6, 50, 51, 20))
self.label_2.setObjectName("label_2")
self.lineEdit_Time = QtWidgets.QLineEdit(self.groupBox)
self.lineEdit_Time.setGeometry(QtCore.QRect(60, 20, 61, 20))
self.lineEdit_Time.setObjectName("lineEdit_Time")
self.lineEdit_Increment = QtWidgets.QLineEdit(self.groupBox)
self.lineEdit_Increment.setGeometry(QtCore.QRect(60, 50, 61, 20))
self.lineEdit_Increment.setObjectName("lineEdit_Increment")
self.pushButton_Start = QtWidgets.QPushButton(self.groupBox)
self.pushButton_Start.setGeometry(QtCore.QRect(10, 90, 111, 23))
self.pushButton_Start.setObjectName("pushButton_Start")
self.label = QtWidgets.QLabel(self.groupBox)
self.label.setGeometry(QtCore.QRect(10, 20, 47, 13))
self.label.setObjectName("label")
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 21))
self.menubar.setObjectName("menubar")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
self.pushButton_Start.clicked.connect(self.update)
global inc
inc = self.lineEdit_Time.text()
global newTime
newTime = self.lineEdit_Increment.text()
def update(self):
global time
time = time.addSecs(-1)
global argument
global new
data = time.toString("mmss")
print(data)
argument.write(data.encode());
if data == '0000':
timer.stop()
global countDown
countDown = data
return time
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.label_2.setText(_translate("MainWindow", "Increment"))
self.pushButton_Start.setText(_translate("MainWindow", "START"))
self.label.setText(_translate("MainWindow", "Time"))
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
global time
timer = QtCore.QTimer()
time = QtCore.QTime(0, inc,0)
timer.timeout.connect(update)
timer.start(newTime)
MainWindow.show()
sys.exit(app.exec_())
Something like this? You want to access your increment and start time from the text values of the self.lineEdit_Time and self.lineEdit_Increment widgets. Then you use this in a start_timer method, which you connect to the start buttons clicked signal.
In the start_timer method, we create a timer which is a member of the main_window object,
and this timer's timeout signal is connected to our update_clock method, which updates the countdown based on the self.increment value.
class Ui_MainWindow(object):
#...
self.pushButton_Start.pressed.connect(self.start_timer)
def start_timer(self):
self.countdown = int(self.lineEdit_Time.text())
self.increment = int(self.lineEdit_Increment.text())
self.countdownTimer = QtCore.QTimer()
self.countdownTimer.timeout.connect(self.update_clock)
self.countdownTimer.start(1000) # fires every 1000ms = 1s
def update_clock(self):
self.countdown -= self.increment
#update a clock label that shows the countdown value
self.clockLabel.setText(self.countdown)
#or just print the vaule for now
print(self.countdown)
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'messagerGUI.ui'
#
# Created by: PyQt5 UI code generator 5.13.0
#
# WARNING! All changes made in this file will be lost!
# ""
from PyQt5 import QtCore, QtGui, QtWidgets
import socket
import threading
class Ui_MainWindow(object):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
header = 12
connections = []
ip = socket.gethostname()
port = 1234
connections_allowed = 3
sock.bind((ip, port))
sock.listen(connections_allowed)
new_message = False
def start(self):
while True:
self.conn, self.addr = self.sock.accept()
threading.Thread(target=self.receive_data, args=[
self.conn], daemon=True).start()
self.connections.append(self.conn)
def receive_data(self, conn):
self.reply = ""
while True:
try:
message_lenth = conn.recv(self.header)
lenth_of_message = message_lenth.decode("utf-8")
if not message_lenth:
break
elif message_lenth:
data = conn.recv(int(lenth_of_message))
self.reply = data.decode("utf-8")
print(self.reply)
self.new_message = True
for connection in self.connections:
if connection != conn:
connection.send(message_lenth.encode("utf-8"))
connection.send(self.reply.encode("utf-8"))
except:
break
def packing_data_lenth(self, text):
return len(text) * 4
def send_data(self, data):
try:
for connection in self.connections:
connection.send(
bytes(str(self.packing_data_lenth(data)), "utf-8"))
connection.send(bytes(data, "utf-8"))
except:
pass
def setupUi(self, MainWindow):
threading.Thread(target=self.start, daemon=True).start()
MainWindow.setObjectName("MainWindow")
MainWindow.resize(499, 367)
MainWindow.setStyleSheet("background-color: #113e4a;")
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.horizontalLayout = QtWidgets.QHBoxLayout(self.centralwidget)
self.horizontalLayout.setContentsMargins(5, 5, 5, 5)
self.horizontalLayout.setSpacing(5)
self.horizontalLayout.setObjectName("horizontalLayout")
self.info = QtWidgets.QWidget(self.centralwidget)
sizePolicy = QtWidgets.QSizePolicy(
QtWidgets.QSizePolicy.Maximum, QtWidgets.QSizePolicy.Minimum)
sizePolicy.setHeightForWidth(
self.info.sizePolicy().hasHeightForWidth())
self.info.setSizePolicy(sizePolicy)
self.info.setMinimumSize(QtCore.QSize(178, 357))
self.info.setStyleSheet("background-color: #429178;\n"
"border-radius: 2px;")
self.info.setObjectName("info")
self.verticalLayout_3 = QtWidgets.QVBoxLayout(self.info)
self.verticalLayout_3.setObjectName("verticalLayout_3")
self.label_3 = QtWidgets.QLabel(self.info)
self.label_3.setObjectName("label_3")
self.verticalLayout_3.addWidget(self.label_3)
spacerItem = QtWidgets.QSpacerItem(
20, 317, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)
self.verticalLayout_3.addItem(spacerItem)
self.horizontalLayout.addWidget(self.info)
self.message_widget()
self.chat_area = QtWidgets.QWidget(self.centralwidget)
sizePolicy = QtWidgets.QSizePolicy(
QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Minimum)
sizePolicy.setHeightForWidth(
self.chat_area.sizePolicy().hasHeightForWidth())
self.chat_area.setSizePolicy(sizePolicy)
self.chat_area.setMinimumSize(QtCore.QSize(306, 0))
self.chat_area.setStyleSheet("background-color: #429178;")
self.chat_area.setObjectName("chat_area")
self.verticalLayout = QtWidgets.QVBoxLayout(self.chat_area)
self.verticalLayout.setContentsMargins(2, 2, 2, 2)
self.verticalLayout.setSpacing(1)
self.verticalLayout.setObjectName("verticalLayout")
self.messages_area = QtWidgets.QScrollArea(self.chat_area)
sizePolicy = QtWidgets.QSizePolicy(
QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.MinimumExpanding)
sizePolicy.setHeightForWidth(
self.messages_area.sizePolicy().hasHeightForWidth())
self.messages_area.setSizePolicy(sizePolicy)
self.messages_area.setMinimumSize(QtCore.QSize(0, 259))
self.messages_area.setStyleSheet("background-color: #113e4a;")
self.messages_area.setWidgetResizable(True)
self.messages_area.setObjectName("messages_area")
self.scrollAreaWidgetContents = QtWidgets.QWidget()
self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, 0, 300, 316))
sizePolicy = QtWidgets.QSizePolicy(
QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Minimum)
sizePolicy.setHeightForWidth(
self.scrollAreaWidgetContents.sizePolicy().hasHeightForWidth())
self.scrollAreaWidgetContents.setSizePolicy(sizePolicy)
self.scrollAreaWidgetContents.setLayoutDirection(QtCore.Qt.LeftToRight)
self.scrollAreaWidgetContents.setObjectName("scrollAreaWidgetContents")
self.verticalLayout_2 = QtWidgets.QVBoxLayout(
self.scrollAreaWidgetContents)
self.verticalLayout_2.setSizeConstraint(
QtWidgets.QLayout.SetNoConstraint)
self.verticalLayout_2.setSpacing(6)
self.verticalLayout_2.setObjectName("verticalLayout_2")
spacerItem1 = QtWidgets.QSpacerItem(
20, 40, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.MinimumExpanding)
self.verticalLayout_2.addItem(spacerItem1)
self.messages_area.setWidget(self.scrollAreaWidgetContents)
self.verticalLayout.addWidget(self.messages_area)
self.input_area = QtWidgets.QWidget(self.chat_area)
self.input_area.setMinimumSize(QtCore.QSize(0, 30))
self.input_area.setObjectName("input_area")
self.horizontalLayout_2 = QtWidgets.QHBoxLayout(self.input_area)
self.horizontalLayout_2.setContentsMargins(1, 1, 1, 1)
self.horizontalLayout_2.setSpacing(1)
self.horizontalLayout_2.setObjectName("horizontalLayout_2")
self.userInput = QtWidgets.QLineEdit(self.input_area)
sizePolicy = QtWidgets.QSizePolicy(
QtWidgets.QSizePolicy.MinimumExpanding, QtWidgets.QSizePolicy.Minimum)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.userInput.sizePolicy().hasHeightForWidth())
self.userInput.setSizePolicy(sizePolicy)
self.userInput.setMinimumSize(QtCore.QSize(22, 32))
font = QtGui.QFont()
font.setPointSize(12)
self.userInput.setFont(font)
self.userInput.setStyleSheet("background-color: rgb(17, 62, 74);\n"
"color: #d0e8ce;\n"
"border: 0px;")
self.userInput.setInputMethodHints(QtCore.Qt.ImhNone)
self.userInput.setFrame(True)
self.userInput.setDragEnabled(True)
self.userInput.setPlaceholderText("Type a message")
self.userInput.setObjectName("userInput")
self.horizontalLayout_2.addWidget(self.userInput)
self.sendButton = QtWidgets.QPushButton(self.input_area)
sizePolicy = QtWidgets.QSizePolicy(
QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Minimum)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.sendButton.sizePolicy().hasHeightForWidth())
self.sendButton.setSizePolicy(sizePolicy)
self.sendButton.setMinimumSize(QtCore.QSize(12, 32))
font = QtGui.QFont()
font.setPointSize(12)
self.sendButton.setFont(font)
self.sendButton.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))
self.sendButton.setMouseTracking(True)
self.sendButton.setObjectName("sendButton")
self.sendButton.clicked.connect(self.get_user_input)
self.horizontalLayout_2.addWidget(self.sendButton)
self.verticalLayout.addWidget(self.input_area)
self.horizontalLayout.addWidget(self.chat_area)
MainWindow.setCentralWidget(self.centralwidget)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
In this part(function message_widget) i get an error:
self.widget = QtWidgets.QWidget(self.scrollAreaWidgetContents)
AttributeError: 'Ui_MainWindow' object has no attribute 'scrollAreaWidgetContents'
Even though i did something similar in the get_user_input function,
i know the code is a mess but the only part that is not working is this part,
the socket server and client are both working properly, i tested printing the
text received in the terminal, so yeah, i wanna know why do i get this error?
def message_widget(self):
self.widget = QtWidgets.QWidget(self.scrollAreaWidgetContents)
sizePolicy = QtWidgets.QSizePolicy(
QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Minimum)
sizePolicy.setHeightForWidth(
self.widget.sizePolicy().hasHeightForWidth())
self.widget.setSizePolicy(sizePolicy)
self.widget.setMinimumSize(QtCore.QSize(158, 25))
self.widget.setLayoutDirection(QtCore.Qt.LeftToRight)
self.widget.setStyleSheet(
"background-color: #d35439;\n" "border-radius: 4px;")
self.widget.setObjectName("widget")
self.horizontalLayout_3 = QtWidgets.QHBoxLayout(self.widget)
self.horizontalLayout_3.setObjectName("horizontalLayout_3")
self.label = QtWidgets.QLabel(self.widget)
self.label.setScaledContents(True)
self.label.setObjectName("label")
self.label.text(self.reply)
self.horizontalLayout_3.addWidget(self.label)
self.verticalLayout_2.addWidget(self.widget)
def get_user_input(self):
self.user_msg = self.userInput.text()
threading.Thread(target=self.send_data, args=[
self.user_msg], daemon=True).start()
self.widget_2 = QtWidgets.QWidget(self.scrollAreaWidgetContents)
sizePolicy = QtWidgets.QSizePolicy(
QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Minimum)
sizePolicy.setHeightForWidth(
self.widget_2.sizePolicy().hasHeightForWidth())
self.widget_2.setSizePolicy(sizePolicy)
self.widget_2.setMinimumSize(QtCore.QSize(182, 25))
self.widget_2.setLayoutDirection(QtCore.Qt.RightToLeft)
self.widget_2.setStyleSheet("background-color: rgb(236, 172, 55);\n"
"border-radius: 4px;")
self.widget_2.setObjectName("widget_2")
self.horizontalLayout_4 = QtWidgets.QHBoxLayout(self.widget_2)
self.horizontalLayout_4.setObjectName("horizontalLayout_4")
self.label_2 = QtWidgets.QLabel(self.widget_2)
self.label_2.setLayoutDirection(QtCore.Qt.RightToLeft)
self.label_2.setAlignment(
QtCore.Qt.AlignRight | QtCore.Qt.AlignTrailing | QtCore.Qt.AlignVCenter)
self.label_2.setObjectName("label_2")
self.label_2.setText(self.user_msg)
self.horizontalLayout_4.addWidget(self.label_2)
self.verticalLayout_2.addWidget(self.widget_2)
self.userInput.setText("")
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "PadoMessager"))
self.label_3.setText(_translate("MainWindow", "Server"))
self.sendButton.setText(_translate("MainWindow", "Send"))
self.sendButton.setShortcut(_translate("MainWindow", "Return"))
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
You think it exists, but when you call message_widget() it does not exist yet.
In fact, you are calling that function before this line:
self.scrollAreaWidgetContents = QtWidgets.QWidget()
So, it could work if you put that function at least after creating that widget.
Unfortunately, there are other serious issues with your code.
The most important one is that you are modifying the output of pyuic to create your program, which is highly discouraged (and the WARNING message at the beginning should be a hint).
The python scripts generated from UI files should NEVER be edited, but used as an import in your actual program files. The most obvious reason is that as soon as you want to do some changes in the ui, you'll find yourself in the mess of trying to merge the new generated code with what you've written so far.
To know more about this, read the documentation about using Designer.
Other issues in your code:
threading in Qt should be used with Qt's own QThread as much as possible;
UI objects should never be accessed nor modified by an external thread; to do that you have to use a QThread, and communicate with the main Qt thread using signals and slots;
QLabel.text() does not accept parameters, as it is used to access the text property; to set the text of a label, use setText();
I've been working on this code as part of my school project and i don't seem to be getting anywhere. My problem is when i try add the text from a file to my QlistWidget my program crashes. Firstly I want to know if this will add the files at the directory (each line in movieDir.txt is a directory) to the QlistWidget, secondly I'm not even sure if I'm using the right widget or if it should be QlistView. Also how would i make it so the currently selected item in the listWidget shows details in the text box (e.g. size of the file).
I'm also looking for this to be done on start up so if someone can please tell me where to the the addItems(self) that would be greatly appreciated. I'm new to using classes as we have been neglected to be taught this in school.
I'm running PyQt5 on windows 7
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'input.ui'
#
# Created by: PyQt5 UI code generator 5.6
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(764, 500)
MainWindow.setMinimumSize(QtCore.QSize(764, 353))
MainWindow.setMaximumSize(QtCore.QSize(764, 500))
self.centralWidget = QtWidgets.QWidget(MainWindow)
self.centralWidget.setObjectName("centralWidget")
self.verticalLayout = QtWidgets.QVBoxLayout(self.centralWidget)
self.verticalLayout.setContentsMargins(11, 11, 11, 11)
self.verticalLayout.setSpacing(6)
self.verticalLayout.setObjectName("verticalLayout")
self.horizontalLayout_2 = QtWidgets.QHBoxLayout()
self.horizontalLayout_2.setContentsMargins(11, 11, 11, 11)
self.horizontalLayout_2.setSpacing(6)
self.horizontalLayout_2.setObjectName("horizontalLayout_2")
self.pushButton_5 = QtWidgets.QPushButton(self.centralWidget)
self.pushButton_5.setObjectName("pushButton_5")
self.horizontalLayout_2.addWidget(self.pushButton_5)
self.verticalLayout.addLayout(self.horizontalLayout_2)
self.verticalLayout_4 = QtWidgets.QVBoxLayout()
self.verticalLayout_4.setContentsMargins(11, 11, 11, 11)
self.verticalLayout_4.setSpacing(6)
self.verticalLayout_4.setObjectName("verticalLayout_4")
self.horizontalLayout_4 = QtWidgets.QHBoxLayout()
self.horizontalLayout_4.setContentsMargins(11, 11, 11, 11)
self.horizontalLayout_4.setSpacing(6)
self.horizontalLayout_4.setObjectName("horizontalLayout_4")
self.listView = QtWidgets.QListView(self.centralWidget)
self.listView.setDragDropMode(QtWidgets.QAbstractItemView.DragDrop)
self.listView.setViewMode(QtWidgets.QListView.ListMode)
self.listView.setObjectName("listView")
self.horizontalLayout_4.addWidget(self.listView)
self.textEdit = QtWidgets.QTextEdit(self.centralWidget)
self.textEdit.setObjectName("textEdit")
self.horizontalLayout_4.addWidget(self.textEdit)
self.verticalLayout_4.addLayout(self.horizontalLayout_4)
self.verticalLayout.addLayout(self.verticalLayout_4)
self.horizontalSlider = QtWidgets.QSlider(self.centralWidget)
self.horizontalSlider.setOrientation(QtCore.Qt.Horizontal)
self.horizontalSlider.setObjectName("horizontalSlider")
self.verticalLayout.addWidget(self.horizontalSlider)
self.verticalLayout_2 = QtWidgets.QVBoxLayout()
self.verticalLayout_2.setContentsMargins(11, 11, 11, 11)
self.verticalLayout_2.setSpacing(6)
self.verticalLayout_2.setObjectName("verticalLayout_2")
self.horizontalLayout = QtWidgets.QHBoxLayout()
self.horizontalLayout.setContentsMargins(11, 11, 11, 11)
self.horizontalLayout.setSpacing(6)
self.horizontalLayout.setObjectName("horizontalLayout")
self.pushButton_3 = QtWidgets.QPushButton(self.centralWidget)
self.pushButton_3.setObjectName("pushButton_3")
self.horizontalLayout.addWidget(self.pushButton_3)
self.pushButton_2 = QtWidgets.QPushButton(self.centralWidget)
self.pushButton_2.setObjectName("pushButton_2")
self.horizontalLayout.addWidget(self.pushButton_2)
self.pushButton = QtWidgets.QPushButton(self.centralWidget)
self.pushButton.setObjectName("pushButton")
self.horizontalLayout.addWidget(self.pushButton)
self.horizontalLayout_3 = QtWidgets.QHBoxLayout()
self.horizontalLayout_3.setContentsMargins(11, 11, 11, 11)
self.horizontalLayout_3.setSpacing(6)
self.horizontalLayout_3.setObjectName("horizontalLayout_3")
self.dial = QtWidgets.QDial(self.centralWidget)
self.dial.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))
self.dial.setMouseTracking(True)
self.dial.setObjectName("dial")
self.horizontalLayout_3.addWidget(self.dial)
self.pushButton_4 = QtWidgets.QPushButton(self.centralWidget)
self.pushButton_4.setObjectName("pushButton_4")
self.horizontalLayout_3.addWidget(self.pushButton_4)
self.horizontalLayout.addLayout(self.horizontalLayout_3)
self.verticalLayout_2.addLayout(self.horizontalLayout)
self.verticalLayout.addLayout(self.verticalLayout_2)
MainWindow.setCentralWidget(self.centralWidget)
self.menuBar = QtWidgets.QMenuBar(MainWindow)
self.menuBar.setGeometry(QtCore.QRect(0, 0, 764, 21))
self.menuBar.setObjectName("menuBar")
MainWindow.setMenuBar(self.menuBar)
self.mainToolBar = QtWidgets.QToolBar(MainWindow)
self.mainToolBar.setObjectName("mainToolBar")
MainWindow.addToolBar(QtCore.Qt.TopToolBarArea, self.mainToolBar)
self.statusBar = QtWidgets.QStatusBar(MainWindow)
self.statusBar.setObjectName("statusBar")
MainWindow.setStatusBar(self.statusBar)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
self.pushButton_5.clicked.connect(self.addItem)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.pushButton_5.setText(_translate("MainWindow", "Show Movies"))
self.pushButton_3.setText(_translate("MainWindow", "Fast-Forward"))
self.pushButton_2.setText(_translate("MainWindow", "Pause/Play"))
self.pushButton.setText(_translate("MainWindow", "Rewind"))
self.pushButton_4.setText(_translate("MainWindow", "Full Screen"))
def addItem(self):
with open('movieDir.txt', 'r') as movieDir:
for row in movieDir:
listWidget.addItem(row)
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
self.listWidget = QtWidgets.QListWidget(self.centralWidget)
self.listWidget.setObjectName("listWidget")
self.horizontalLayout_4.addWidget(self.listWidget)
with open('moviesDir.txt','r') as movieDir:
for movie in movieDir:
self.listWidget.addItem(movie)
This did what i asked, but it only shows it as text, is there a way to show the files at the directory instead of the directory as a string?
#This is the example code for loading files and content inside the file to QtGui.QListWidget
#It is PyQt4, but you can try with PyQt5 with small changes.
#If your are not expecting this answer, sorry.
import sys, os
from PyQt4 import QtGui, QtCore
class Window (QtGui.QWidget):
def __init__(self, parent=None):
super(Window, self).__init__(parent)
self.verticalLayout = QtGui.QVBoxLayout (self)
self.verticalLayout.setObjectName ('verticalLayout')
self.horizontalLayout = QtGui.QHBoxLayout()
self.horizontalLayout.setObjectName('horizontalLayout')
self.listWidget = QtGui.QListWidget(self)
self.listWidget.setObjectName('listView')
self.listWidget.setAlternatingRowColors (True)
self.horizontalLayout.addWidget(self.listWidget)
self.verticalLayout1 = QtGui.QVBoxLayout()
self.verticalLayout1.setSpacing(10)
self.verticalLayout1.setObjectName('verticalLayout')
self.pushButton = QtGui.QPushButton(self)
self.pushButton.setObjectName('pushButton')
self.pushButton.setText('Load File Content')
self.pushButton_2 = QtGui.QPushButton(self)
self.pushButton_2.setObjectName('pushButton_2')
self.pushButton_2.setText('Load File')
self.verticalLayout1.addWidget(self.pushButton)
self.verticalLayout1.addWidget(self.pushButton_2)
spacerItem = QtGui.QSpacerItem(20, 40, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding)
self.verticalLayout1.addItem (spacerItem)
self.horizontalLayout.addLayout(self.verticalLayout1)
self.verticalLayout.addLayout(self.horizontalLayout)
self.pushButton.clicked.connect (self.loadFileContent)
self.pushButton_2.clicked.connect (self.loadFiles)
def loadFileContent (self) :
openFiles = QtGui.QFileDialog.getOpenFileName (self, 'Open File', 'c:/', 'txt (*.txt)')
if openFiles :
data = open (str(openFiles), 'r')
dataList = data.readlines ()
self.listWidget.clear ()
for eachLine in dataList :
if len(eachLine.strip())!=0 :
self.listWidget.addItem(eachLine.strip())
def loadFiles (self) :
getDirectory = QtGui.QFileDialog.getExistingDirectory(self, 'Browse', 'C:/')
if getDirectory :
fileList = os.listdir (str(getDirectory))
if fileList :
self.listWidget.clear ()
for eachFile in fileList :
self.listWidget.addItem (eachFile)
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
w = Window()
w.show()
sys.exit(app.exec_())
#Thanks,
#Subin Gopi