Move the cursor to the start after auto-completion - python

I have a small program where I used a line edit for auto-completion. After selecting the text, my cursor goes to end of the text. So how to set my cursor to the starting position?
My code:
import sys
from PyQt4.QtCore import Qt
from PyQt4.QtGui import QApplication, QCompleter, QLineEdit, QStringListModel
def get_data(model):
model.setStringList(["completion_xxxxxxxxxx", "data_yyyyyyyyyy", "goes_ccccccccc", "here"])
if __name__ == "__main__":
app = QApplication(sys.argv)
edit = QLineEdit()
edit.setCursorPosition(0)
completer = QCompleter()
edit.setCompleter(completer)
model = QStringListModel()
completer.setModel(model)
get_data(model)
edit.show()
sys.exit(app.exec_())
But I want to show it like this:

Assuming you want the cursor to move after the completion has finished, you can use the completer's activated signal with a single-shot timer, like this:
completer.activated.connect(
lambda: QTimer.singleShot(0, lambda: edit.home(False)))

Related

Can't create custom widget in tray menu with python pyside2

Not much info I've found, but looks like this snippet should works:
import sys
from PySide2.QtWidgets import QApplication, QMenu, QPushButton, QSystemTrayIcon, QWidgetAction
app = QApplication(sys.argv)
menu = QMenu()
button = QPushButton("yoba")
action = QWidgetAction(menu)
action.setDefaultWidget(button)
menu.addAction(action)
menu.addAction("Quit").triggered.connect(sys.exit)
tray = QSystemTrayIcon()
tray.setContextMenu(menu)
tray.show()
sys.exit(app.exec_())
But, I see only Quit item and empty item above, no push button appear. So, the question is "how to add custom widgets to tray menu?"
Ok, looks like this is a bug: https://bugreports.qt.io/browse/QTBUG-26840
Since if call menu.show() instead of tray.show() everything is fine.

PyQT5's input application dialogue box is not staying on windows 10 screen

I am developing a PyQt5 application which takes an input from the user in a string format and then utilise that variable further in the code.
Problem: The input box code when called from within a while loop (Ideally the box should stay and wait for the input from the user, thereby holding the while loop execution as well), instead it does not stay on the screen, it flashes and disappears in a fraction of seconds when executing the script on windows 10. But when I execute the code snippet mentioned below separately, then this type of problem does not appear.
Code Snippet
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QInputDialog, QLineEdit, QLabel
def call_qt():
app = QApplication(sys.argv)
gui = QWidget()
text, ok = QInputDialog.getText(gui, "User Input",
"""Do you wish to Continue [Y/N]?""")
#print(text, ok)
if ok:
app.exit()
else:
app.exit()
return text
print(call_qt())
I am not able to figure out, What could be the problem with this code snippet. Could you please help me with this? Also, I am new to PyQt5.
Confusion: The same problem does not exist on Ubuntu 18.
The problem with this part is the process handling in windows. Do threading of the QT application and call this thread inside your while loop. This should solve the problem.
from queue import Queue
que = Queue()
def call_qt(out_que):
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QInputDialog, QLineEdit, QLabel
app = QApplication(sys.argv)
gui = QWidget()
text, ok = QInputDialog.getText(gui, "User Input",
"""Do you wish to Continue [Y/N]?""")
#print(text, ok)
if ok:
app.exit()
else:
app.exit()
out_que.put()
while True:
t = Threading.thread(target=call_qt, args=(que,))
t.start()
t.join()
print("text: ",que.get())
same problem should happen on ubuntu. As you hit OK, application terminates itself and you wont be able to see output. Try this code, it prints the result on widget
import sys
from PyQt5.QtWidgets import (QApplication, QWidget, QInputDialog, QVBoxLayout, QLabel)
def call_qt(main_widow):
text, ok = QInputDialog.getText(main_widow, "User Input", "Do you wish to Continue [Y/N]?")
return text, ok
if __name__ == '__main__':
app = QApplication(sys.argv)
main_widow = QWidget()
layout = QVBoxLayout()
label = QLabel()
layout.addWidget(label)
main_widow.setLayout(layout)
main_widow.show()
text, ok = call_qt(main_widow)
# if ok:
# sys.exit()
label.setText(text)
sys.exit(app.exec_())

Detect Ctrl+S ion QTextedit?

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_())

Get the selected text content from other programs

When I am using other programs (e.g. opening a pdf or word), I will select some text contents (like a word or paragraph) by using the mouse. I want my python program to get this text content. How to do this using PyQt, or some other Python library?
This is an easy task, you haven't specified the pyqt version, so I'll post the solution for PyQt4, here you go:
from PyQt4.QtCore import QObject, pyqtSlot, SIGNAL, SLOT
from PyQt4.QtGui import QApplication, QMessageBox
import sys
class MyClipboard(QObject):
#pyqtSlot()
def changedSlot(self):
if(QApplication.clipboard().mimeData().hasText()):
QMessageBox.information(None, "Text has been copied somewhere!",
QApplication.clipboard().text())
def main():
app = QApplication(sys.argv)
listener = MyClipboard()
app.setQuitOnLastWindowClosed(False)
QObject.connect(QApplication.clipboard(), SIGNAL(
"dataChanged()"), listener, SLOT("changedSlot()"))
sys.exit(app.exec_())
if __name__ == '__main__':
main()

how to add image with text in qlistwidget pyqt4 python?

How to add image/icon with text in a qlistwidget in pyqt4 python? I want to add an icon with text just like a chat system. thanks
I have tried this right now and it works, supposing you have a file named tick.png in the same folder as this script.
import sys
from PyQt4 import QtGui, QtCore
from PyQt4.QtGui import QApplication, QDialog, QListWidgetItem, QListWidget, QIcon
def main():
app = QtGui.QApplication(sys.argv)
window = QDialog()
list = QListWidget( window )
itm = QListWidgetItem( "Tick" );
itm.setIcon(QIcon(r"tick.png"));
list.addItem(itm);
window.show( )
sys.exit(app.exec_())
if __name__ == '__main__':
main()
The chat-like-icon system may be different from this, but right now I don't see a way to have a QListWidgetItem with multiple smileys and text.
You may think of smileys as a particular case of a QListWidgetItem where the text is blank and only the icon is present.
Another solution is using a read-only QTextEdit as chatboard and have the user typing its text + icon + text (etc.) in a separate editable QTextEdit. Then, when he presses the send button, append everything he typed to the read-only QTextEdit.
import sys
from PyQt4 import QtGui, QtCore
from PyQt4.QtGui import QApplication, QDialog, QListWidgetItem, QListWidget, QIcon, QTextEdit, QTextDocumentFragment
def main():
app = QtGui.QApplication(sys.argv)
window = QDialog()
list = QListWidget( window )
textEditor = QTextEdit( window );
textEditor.setReadOnly( True )
tick_icon = QTextDocumentFragment.fromHtml(r"<img src='tick.png'>");
textEditor.insertPlainText ( " ValiumKnight writes: " )
textEditor.textCursor().insertFragment(tick_icon);
textEditor.insertPlainText ( " Hello World " )
textEditor.textCursor().insertFragment(tick_icon);
textEditor.textCursor().insertFragment(tick_icon);
textEditor.textCursor().insertFragment(tick_icon);
window.show( )
sys.exit(app.exec_())
if __name__ == '__main__':
main()
Bye!

Categories

Resources