I'd like to use Qt's virtual keyboard (Qt5.11.1 or newer?) in my python3 (3.6) project on Win10, but I'm stuck.
I have anaconda environment and I'm quite sure the Virtual keyboard is also somewhere in there, because I can find some folders with correct name.
What should the main program look like, besides the obvious, to virtual keyboard pop up when an input widget gets selected?
import sys
from qtpy.QtWidgets import QApplication, QDialog, QVBoxLayout, QSpinBox
class Test(QDialog):
def __init__(self):
super(Test, self).__init__()
layout = QVBoxLayout()
self.setLayout(layout)
for i in range(2):
layout.addWidget(QSpinBox())
if __name__ == '__main__':
import os
os.environ["QT_IM_MODULE"] = "qtvirtualkeyboard"
app = QApplication(sys.argv)
dialog = Test()
sys.exit(dialog.exec())
edit: to be clear, i don't want to reinvent or customize the wheel, just use it.
Related
Is there a way to change default menu title for native menu on MacOS for a simple pyqt5 app?
I'm trying to change "Python" menu entry on above image. Is there a way to rename it? Can I hide it somehow?
This code prints only "File":
menubar = self.menuBar()
for item in menubar.actions():
print(item.text())
menubar.setNativeMenuBar(False) doesn't help too (just move "File" into the MainWindow).
Update Sample app code:
from PyQt5 import QtCore, QtWidgets, uic
import sys
class Ui(QtWidgets.QMainWindow):
def __init__(self):
super(Ui, self).__init__()
# QtCore.QCoreApplication.setApplicationName('QtFoo') # doesn't work
uic.loadUi('App.ui', self)
self.show()
# app = QtWidgets.QApplication(sys.argv)
app = QtWidgets.QApplication(["MyCoolApp"])
# app.setApplicationName("QtFoo") # doesn't work
# app.setApplicationDisplayName("Display Name")
window = Ui()
app.exec()
If you are not willing to package your app, you could create a temporary symbolic link to python as described here. This link can be used to execute python apps while displaying a custom name in the title bar:
go to the location of your app (e.g. my_app.py) file in the terminal
create symbolic link (replace location to your python interpreter, replace "BeautifulNaming" with desired name)
ln -s /Users/Christian/miniconda3/bin/python BeautifulNaming
call link to python with your script
./BeautifulNaming my_app.py
The "python" in the system menu bar appears because you run the script from the python, as soon as you package the application the title will disappear. For example the following code
# FileName PyQt5MenuProblem.py
import sys
from PyQt5.QtWidgets import QApplication,QMainWindow
class AppTest(QMainWindow):
def __init__(self):
QMainWindow.__init__(self)
self.setWindowTitle("My application")
self._createMenuBar()
def _createMenuBar(self):
self.menuBar = self.menuBar()
self.menuBar.setNativeMenuBar(False)
fileMenu = self.menuBar.addMenu("&File")
editMenu = self.menuBar.addMenu("&Edit")
if __name__== "__main__":
app = QApplication(sys.argv)
plotWindow = AppTest()
plotWindow.showMaximized()
sys.exit(app.exec_())
after packaging with
pyinstaller --onefile PyQt5MenuProblem.py
looks like
Key words: MacOS, User Interface, LSUIElement, pyinstaller, pyqt5
I am new to PyQt and I am learning to make GUIs based on online tutorials I found. One of the examples in the tutorials uses an icon, here is the code from the tutorial:
import sys
from PyQt5.QtWidgets import QMainWindow, QAction, qApp, QApplication
from PyQt5.QtGui import QIcon
class Example(QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
exitAct = QAction(QIcon('exit24.png'), 'Exit', self)
exitAct.setShortcut('Ctrl+Q')
exitAct.triggered.connect(qApp.quit)
self.toolbar = self.addToolBar('Exit')
self.toolbar.addAction(exitAct)
self.setGeometry(300, 300, 300, 200)
self.setWindowTitle('Toolbar')
self.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
The output according to the tutorial should be
But for me it's this
As I said, I just started with PyQt and I just installed PyQt through pip
pip install PyQt5
I'm using Python3.6 and PyQt5. Any help is greatly appreciated!
Yes, PyQt5 does come with a list of default icons. You can find them here:
List of PyQt Icons
However, it seems the "exit" icon from the tutorial you refrenced used a local icon downloaded on their computer. You need to download the same icon and name it 'exit24.png' next to your python file.
So, I'm making a QTextEdit that edits a text file. I got the loading and saving working fine with buttons. But I got the habit of pressing Ctrl+S to save every time I paste something into the textedit because I used that in Notepad before. So I've been trying to implement it. But I can't wrap my head around how to detect and execute my save function. Lets call it savetext.
I've been going around trying to get keyPressEvent to work, but I just don't understand how it works. So I've been pretty helpless in trying to learn it.
My heavily simplified code looks like this:
class GUI(QProcess):
def init etc...
"Button creations and connect to save/load function"
self.textedit=QTextEdit()
def savetext(self):
code
def loadtext(self):
code
Now, how do I detect a key combination being detected in the QTextEdit, or anywhere in my program for that matter, and cause it to do savetext? In my case, Ctrl+S, though I'd just love a general explanation so I could apply it to any combo.
Use QShortcut and QKeySequence
from PyQt5.QtWidgets import QApplication, QTextEdit, QShortcut
from PyQt5.QtGui import QKeySequence
import sys
def slot():
print("Ctrl+S")
app = QApplication(sys.argv)
textedit=QTextEdit()
shortcut = QShortcut(QKeySequence("Ctrl+S"), textedit)
shortcut.activated.connect(slot)
textedit.show()
sys.exit(app.exec_())
You can probably use QShortcut, and right now it will activate only when textedit in focus. If you want to change the behavior please take a look here
Here is a example
import sys
from PyQt4 import QtGui, QtCore
class Window(QtGui.QWidget):
def __init__(self):
QtGui.QWidget.__init__(self)
layout = QtGui.QVBoxLayout(self)
self.edit = QtGui.QTextEdit()
layout.addWidget(self.edit)
self.button = QtGui.QPushButton('Test')
layout.addWidget(self.button)
foo = QtGui.QShortcut(QtGui.QKeySequence("Ctrl+S"), self.edit, self.saveCall, context=QtCore.Qt.WidgetShortcut)
def saveCall(self):
self.edit.append('Please save me')
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
win = Window()
win.show()
sys.exit(app.exec_())
This example creates a single QListWidget with its items right-click enabled.
Right-click brings up QMenu. Choosing a menu opens a OS File Browser in a current user's home directory.
After a File Browser is closed QMenu re-appears which is very annoying.
How to avoid this undesirable behavior?
import sys, subprocess
from os.path import expanduser
from PyQt4 import QtGui, QtCore
class Window(QtGui.QWidget):
def __init__(self):
QtGui.QWidget.__init__(self)
layout = QtGui.QVBoxLayout(self)
self.listWidget = QtGui.QListWidget()
self.listWidget.addItems(('One','Two','Three','Four','Five'))
self.listWidget.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
self.listWidget.connect(self.listWidget,QtCore.SIGNAL('customContextMenuRequested(QPoint)'),self.showMenu)
self.menu=QtGui.QMenu()
menuItem=self.menu.addAction('Open Folder')
self.connect(menuItem,QtCore.SIGNAL('triggered()'),self.openFolder)
layout.addWidget(self.listWidget)
def showMenu(self, QPos):
parentPosition=self.listWidget.mapToGlobal(QtCore.QPoint(0, 0))
menuPosition=parentPosition+QPos
self.menu.move(menuPosition)
self.menu.show()
def openFolder(self):
if sys.platform.startswith('darwin'):
subprocess.call(['open', '-R',expanduser('~')])
if sys.platform.startswith('win'):
subprocess.call(['explorer','"%s"'%expanduser('~')])
if __name__ == '__main__':
import sys
app = QtGui.QApplication(sys.argv)
window = Window()
window.show()
sys.exit(app.exec_())
Two ideas come to my mind:
Try adding self as a constructor parameter when defining QMenu(), passing your QWidget as a parent.
Call self.menu.hide() in the openFolder() method.
Tip: instead of using subprocess to open up explorer, there's an arguably better, cross platform solution in Qt called QDesktopServices - see http://pyqt.sourceforge.net/Docs/PyQt4/qdesktopservices.html
I'm using PyQt to develop an application that in Windows, if set in preferences, should be able to start at boot.
I'm releasing this software with PyInstaller as a single executable file; i don't have a proper "installer".
Which is the best way to achieve this? ( = starting at boot)
A possible solution is to add a link in the startup folder, but i have to do it from the software: it's possible? Other ways?
There is an universal path to the Startup folder? Can i have some rights' problem?
try this code (it works for me with py2exe):
import sys
from PyQt4.QtCore import QSettings
from PyQt4.QtGui import (QApplication, QWidget, QCheckBox, QPushButton,
QVBoxLayout)
RUN_PATH = "HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Run"
class MainWidget(QWidget):
def __init__(self,parent=None):
super(MainWidget, self).__init__(parent)
self.settings = QSettings(RUN_PATH, QSettings.NativeFormat)
self.setupUi()
# Check if value exists in registry
self.checkbox.setChecked(self.settings.contains("MainWidget"))
def setupUi(self):
self.checkbox = QCheckBox("Boot at Startup", self)
button = QPushButton("Close", self)
button.clicked.connect(self.close)
layout = QVBoxLayout(self)
layout.addWidget(self.checkbox)
layout.addWidget(button)
def closeEvent(self, event):
if self.checkbox.isChecked():
self.settings.setValue("MainWidget",sys.argv[0]);
else:
self.settings.remove("MainWidget");
event.accept()
if __name__ == '__main__':
app = QApplication(sys.argv)
w = MainWidget()
w.show()
app.exec_()
You may add registry key under [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run], with any name and value "path_to_your_exec". this will require local administrator right, but will work for all users.
The same key but starting with [HKEY_CURRENT_USER] will not require administrator privileges, but will work only for current user.
That registry path is the same for win2k..win7