I have written a python script that manipulates data and then saves it into an excel file with the following function:
def saveData():
table = pd.DataFrame(data)
writer = pd.ExcelWriter('manipulatedData.xlsx')
table.to_excel(writer, 'sheet 1')
writer.save()
I also have the following super basic/minimalistic gui window:
from PyQt4 import QtGui
app = QtGui.QApplication(sys.argv)
window = QtGui.QWidget()
window.setGeometry(500,500,500,500)
window.setWindowTitle("PyQt Test!")
window.setWindowIcon(QtGui.QIcon('pythonLogoSmall.png'))
window.show()
sys.exit(app.exec_())
What I really would like to know is this:
1) How can I let the user of my gui select the location + name for the manipulatedData file?
2) How can I add a "run" button, that starts my python script and manipulates the data, before it saves the manipulated data to the desired location.
PyQt4 has QLineEdit() and QPushButton()
from PyQt4 import QtGui
import sys
# --- functions ---
def my_function(event=None):
print 'Button clicked: event:', event
print linetext.text()
# run your code
# --- main ---
app = QtGui.QApplication(sys.argv)
window = QtGui.QWidget()
# add "layout manager"
vbox = QtGui.QVBoxLayout()
window.setLayout(vbox)
# add place for text
linetext = QtGui.QLineEdit(window)
vbox.addWidget(linetext)
# add button
button = QtGui.QPushButton("Run", window)
vbox.addWidget(button)
# add function to button
button.clicked.connect(my_function)
window.show()
sys.exit(app.exec_())
Related
actually I try to do a displayer of html page. I have some of list of html that I need to display, each page must stay visible while x secondes.
But, after the first page is display, the application crash and the python shell restart in consequence.
On my mind, I would create the window to display the page and close the application because after I will try to display png/jpg, so I need to close app to use Pygame for pictures and re-build the app to display html page after.
My list looking for it :
html page/html page/picture/html page/picture/picture
So I have build a sample code to test in while boucle the displayer :
from PyQt5 import QtWidgets, QtWebEngineWidgets, QtCore
import sys
continuer = True
while continuer:
print("Application created")
# Create application
app = QtWidgets.QApplication(sys.argv)
# Add window
win = QtWidgets.QWidget()
win.setWindowTitle('My first rendering')
# Add layout
layout = QtWidgets.QVBoxLayout()
win.setLayout(layout)
# Create QWebView
view = QtWebEngineWidgets.QWebEngineView()
view.setUrl(QtCore.QUrl('https://google.com'))
# Add QWebView to the layout
layout.addWidget(view)
# Show window, run app
win.show()
QtCore.QTimer.singleShot(7*1000, win.close)
QtCore.QTimer.singleShot(7*1000, app.quit)
print("View displayed")
# While loop
app.exec_()
print('Close Application')
print("End While Loop")
Result after executing
It's probably sys.argv in app var the mistake, but I'm new in Python so I don't know how to fix the problem.
The problem is that QApplication is not necessarily eliminated and therefore you would be creating more than one QApplication what Qt forbids, a better solution is to rethink it verifying that if it does not exist then create a new one:
import sys
from PyQt5 import QtCore, QtWidgets, QtWebEngineWidgets
continuer = True
while continuer:
print("Application created")
# Create application
app = QtWidgets.QApplication.instance()
if app is None:
app = QtWidgets.QApplication(sys.argv)
# Add window
win = QtWidgets.QWidget()
win.setWindowTitle("My first rendering")
# Create QWebEngineView
view = QtWebEngineWidgets.QWebEngineView()
view.setUrl(QtCore.QUrl("https://google.com"))
# Add layout
layout = QtWidgets.QVBoxLayout(win)
win.setLayout(layout)
# Add QWebView to the layout
layout.addWidget(view)
# Show window, run app
win.show()
QtCore.QTimer.singleShot(7 * 1000, win.close)
QtCore.QTimer.singleShot(7 * 1000, app.quit)
print("View displayed")
# While loop
app.exec_()
print("Close Application")
print("End While Loop")
I am having trouble figuring out how to use Qt to create translation files for a python apllication.
I'm using python 2.7, Qt version 5.9.1 and PyQt4 4.12.1 to create my GUI on OSX 10.11.6.
For now I just wanted to translate a few words on my code.
For what I understand, I have to use QtLinguist to open a .ts file, translate the words and create a .qm file, which will then be used by python.
From Qt Linguist page I get that I need to use a .pro project file, that will be read by pylupdate4, etc...
Now, I do I create a .pro file?
I tried running:
$ qmake -project myfile.py
$ pylupdate4 myfile.pro -ts file.ts
but the resulting .pro file can't be read by pylupdate4 (XML error: Parse error at line 1, column 1 [...])
From this Tutorial, I tried:
$ pylupdate4 myfile.py -ts file.ts
Which creates an empty .ts file, that Qt Linguist can't open.
Can someone give my any tip on what might be wrong, the 15 tabs I have open in my browser are not helping.
Here's my python code if you need it:
import sys
import os.path as osp
import os
from PyQt4 import QtGui, QtCore
class MainWindow(QtGui.QWidget):
def __init__(self):
super(MainWindow,self).__init__()
# Set MainWindow geometry, use settings of last session. If it's first session,
# use defaulted settings
self.settings = QtCore.QSettings('Paul',QtCore.QSettings.NativeFormat)
self.resize(self.settings.value("size", QtCore.QSize(500, 300)).toSize())
self.move(self.settings.value("pos", QtCore.QPoint(5, 5)).toPoint());
self.initUI()
def closeEvent(self, e):
#Save MainWindow geometry session when closing the window
self.settings.setValue("size",self.size())
self.settings.setValue("pos",self.pos())
e.accept()
def initUI(self):
self.hbox = QtGui.QVBoxLayout(self) # Create Vertival box layout to put the buttons
self.myButtons = QtGui.QPushButton('button',self) #create push button
self.myButtons.setStyleSheet("""QPushButton { background-color: red; font:bold 20px}""")
self.myButtons.setToolTip('Push this button')
self.myButtons.setText(self.tr(QtCore.QString('yes')))
comboBox=QtGui.QComboBox(self) #create drop down menu
comboBox.addItem('Portugues')
comboBox.addItem('English')
self.hbox.addWidget(comboBox,1,QtCore.Qt.AlignRight) #add drop down menu to box layout
self.hbox.addStretch(3) # set separation between buttons
self.myButtons.clicked.connect(self.buttonClicked) # what should the button do
self.hbox.addWidget(self.myButtons,1,QtCore.Qt.AlignRight) #add button to box layout
self.setWindowTitle('Test2')
self.show()
def buttonClicked(self):
msbox= QtGui.QMessageBox()
choice=msbox.warning(self,'ok',"This button doesn't do anything!!!")
if choice == QtGui.QMessageBox.No:
print('nanan')
else:
print('Bye')
self.settings.setValue("size",self.size());
self.settings.setValue("pos",self.pos());
sys.exit()
def main():
app = QtGui.QApplication(sys.argv)
translator = QtCore.QTranslator()
translator.load("~/basefiles/translations/qt_pt.qm")
app.installTranslator(translator)
ex = MainWindow()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
When you use self.tr you must pass the string, not the QString variable, in your case it changes:
self.myButtons.setText(self.tr(QtCore.QString('yes')))
to
self.myButtons.setText(self.tr("yes"))
And run everything again.
Here is my code for the click button:
run_btn=QtWidgets.QPushButton("Run")
def main():
print ('Starting Program')
run_btn.clicked.connect(main)
But after I click "Run", it just prints "Starting Program" again and again, and the GUI window doesn't disappear:
How can I make the button print it once and go on with the program ?
I am using PyQt5 and Python 3.4.0
Suppose that the QPushButton is inside the main widget (in the example QWidget), to close the window we use the close()
from PyQt5 import QtWidgets
import sys
app = QtWidgets.QApplication(sys.argv)
w = QtWidgets.QWidget()
line1_edit = QtWidgets.QLineEdit()
line2_edit = QtWidgets.QLineEdit()
run_btn=QtWidgets.QPushButton("Run")
def main():
print ('Starting Program')
w.close()
run_btn.clicked.connect(main)
layout = QtWidgets.QVBoxLayout()
layout.addWidget(line1_edit)
layout.addWidget(line2_edit)
layout.addWidget(run_btn)
w.setLayout(layout)
w.show()
sys.exit(app.exec_())
I want to make a P2P chat application.
So I have this sig / slot pieces together myself. What I need to achieve is that I want to enter text in the QLineEdit (named it send_box) and display in the QTextedit (named it main_text).
self.send_box.returnPressed.connect(self.sendData)
and here is the function definition
def sendData(self):
self.main_text.setText ('Hello World')
This works. But only send the "Hello World" to the QTextEdit when I press Enter key.
What I need is to send the text from the send_box (QLineEdit).
To get text from send_box and
replace text in main_text
self.main_text.setText( self.send_box.text() )
append to existing text in main_text
self.main_text.append( self.send_box.text() )
And then you can clear text in send_box
self.send_box.clear()
See doc for Qt5 (it's similar for PyQt5): QTextEdit and QLineEdit
Full example
from PyQt5 import QtGui, QtWidgets
import sys
class MyWindow(QtWidgets.QWidget):
def __init__(self):
super().__init__()
self.vbox = QtWidgets.QVBoxLayout()
self.setLayout(self.vbox)
self.vbox.addWidget(QtWidgets.QLabel(text='Input:'))
self.linetext = QtWidgets.QLineEdit()
self.vbox.addWidget(self.linetext)
self.linetext.returnPressed.connect(self.on_press_enter)
self.vbox.addWidget(QtWidgets.QLabel(text='Output:'))
self.textedit = QtWidgets.QTextEdit()
self.vbox.addWidget(self.textedit)
self.show()
def on_press_enter(self):
# copy from LineText to TextEdit
#self.textedit.setText(self.linetext.text())
self.textedit.append(self.linetext.text())
# clear LineText
self.linetext.clear()
app = QtWidgets.QApplication(sys.argv)
window = MyWindow()
app.exec()
I'm working on a small application for work w/ python and PyQt4 for the GUI. What I'm trying to accomplish is having a tabbed GUI where when a user clicks on a menu item, the action taken adds a tab to the QTabWidget. I'm currently having trouble getting an action to do such a thing. I've tried creating the GUI by hand and with QT designer, but I cant figure out how, if at all possible, to get an action to add a tab to the QTabWidget. This is my python code:
import sys
from PyQt4 import QtGui, uic
class TestGUI(QtGui.QMainWindow):
def __init__(self):
super(TestGUI, self).__init__()
uic.loadUi('TEST.ui', self)
self.show()
self.actionAdd_Tab.triggered.connect(addTab)
def addTab():
print 'This works'
#Add new tab to GUI
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
window = TestGUI()
sys.exit(app.exec_())
Pressing the menu item prints 'This works' to the console, so I know that its calling the addTab() function, but how do I get it to add a Tab?
Let me know if you would like to see the .ui file if it will help
The handler for your action needs to create a tab label, and also a widget for the contents of the tab, so that they can be added to the tabwidget.
As a start, try something like this:
import sys
from PyQt4 import QtGui, uic
class TestGUI(QtGui.QMainWindow):
def __init__(self):
super(TestGUI, self).__init__()
uic.loadUi('TEST.ui', self)
self.actionAdd_Tab.triggered.connect(self.handleAddTab)
def handleAddTab(self):
contents = QtGui.QWidget(self.tabWidget)
layout = QtGui.QVBoxLayout(contents)
# add other widgets to the contents layout here
# i.e. layout.addWidget(widget), etc
self.tabWidget.addTab(contents, 'Tab One')
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
window = TestGUI()
window.show()
sys.exit(app.exec_())
QTabWidget's addTab() method, coincidentally named the same, adds a tab.