PyQt5 : How to complete this code in the function 'dollar()' - python

Please help me to complete this code. I want make a text editor and when I give a number in the input dialog, some text or some symbol or some numbers insert to my text lines to number in input dialog and starts with 1 to input dialog number ... Below is the code, you can know what I want to do.
Please see the code and tell me how can I do this?
from PyQt5.QtWidgets import (QWidget,QApplication,QTextEdit,
QInputDialog,QPushButton,QVBoxLayout)
import sys
class Tbx(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.vbox = QVBoxLayout()
self.btn = QPushButton('ClickMe',self)
self.btn.clicked.connect(self.dollar)
self.te = QTextEdit(self)
self.vbox.addWidget(self.te)
self.vbox.addWidget(self.btn)
self.setLayout(self.vbox)
self.setGeometry(300,300,400,250)
self.setWindowTitle('Application')
self.show()
def dollar(self):
text_1_int , ok = QInputDialog.getInt(self,'HowMany?','Enter How Many dollar do you want ?')
if not ok:
return
try:
current_lines = self.te.toPlainText().split('\n')
new_lines = list()
for dollar_counter in range(1, text_1_int + 1):
word = '$' * dollar_counter
new_lines += [text + word for text in current_lines]
self.te.setPlainText("\n".join(new_lines))
#I want this:
#...Texts in TextEditor at first:
#Hi
#User
#agent
#========================================================================
#...Text in TextEditor when I press the button and give 3 in InputDialog:
#Hi$
#Hi$$
#Hi$$$
#User$
#User$$
#User$$$
#agent$
#agent$$
#agent$$$
#Hi#
#Hi##
#Hi###
#User#
#User##
#User###
#agent#
#agent##
#agent###
#Hi#
#Hi##
#Hi###
#User#
#User##
#User###
#agent#
#agent##
#agent###
#Hi!
#Hi!!
#Hi!!!
#User!
#User!!
#User!!!
#agent!
#agent!!
#agent!!!
#Hi1
#Hi12
#Hi123
#User1
#User12
#User123
#agent1
#agent12
#agent123
#========================================================================
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Tbx()
sys.exit(app.exec_())

You are replacing the the text in your text edit at each iteration.
The easiest (clearer) way to do that, would be to generate all your lines before trying to add it to the text edit.
For example:
def dollar(self):
text_1_int , ok = QInputDialog.getInt(self,'HowMany?','Enter How Many dollar do you want ?')
if not ok:
return
try:
current_lines = self.te.toPlainText().split('\n')
new_lines = list()
for dollar_counter in range(1, text_1_int + 1):
word = '$' * dollar_counter
new_lines += [text + word for text in current_lines]
self.te.setPlainText("\n".join(new_lines))
except:
error_msg = QMessageBox()
error_msg.setIcon(QMessageBox.Critical)
error_msg.setText('Please Enter Just Number')
error_msg.setWindowTitle("Error")
error_msg.exec_()
If I enter 3 in the text input:
Btw, the dollar_counter increment is useless: it will be handled by the for loop.

Related

On_click event on a TwoLineIconListItem in kivy

I have an array of values . I have to show this list in a TwoLineIconListItem in kivy along with an image icon and with other information in a list view. When the user clicks on any of the list item, a popup should come (preferably a dialog) and I have to show the item text selected...Pls do help !!
I could write everything but it seems like I am unable to pass the value to the dialog from my TwoLineIconListItem...the code snippet is here where I need some help to achieve this please...
while counter < len(list_of_names):
self.party_name = list_of_names[counter]
self.party_pic = IconLeftWidget(icon=image_source + "\\" + list_of_names[counter].lower() + ".png")
counter += 1
items = TwoLineIconListItem(text=str(counter) + " : " + self.party_name,
secondary_text=self.party_name_details,
on_release=self.select_item)
items.add_widget(self.party_pic)
list_view.add_widget(items)
screen.add_widget(scroll)
return screen
def select_item(self, obj):
print(obj)
# It's should print the item text selected
close_btn = MDFlatButton(text="Close", on_release=self.close_dialog)
confirm_btn = MDFlatButton(text="I Confirm !", on_release=self.confirm_choice)
self.dialog = MDDialog(title="Please confirm your choice!",
text=self.party_name,
size_hint=(0.7, 1),
buttons=[close_btn, confirm_btn]
)
self.dialog.open()

Passing arguments to functions in tkinter

I'm trying to set up a GUI feature that allows users to click a button, then be quizzed on/input new words in the categories 'nouns,' 'verbs,' 'adjectives,' etc. The program I have set up references .txt files saved in the same directory as the program.
I haven't been able to pass arguments to buttons, and the answers I've found suggest using lambda functions in some simple situations. The program works if I remove all passed arguments and simply assign a specific file (farsi_nouns, etc.) within each function. I'm not able to tell if I'm doing this incorrectly, or if Tkinter is too basic a GUI to pass arguments to functions in this way. Thanks very much for any feedback!
Tkinter ver. 8.5, Python 3.5.2, OSx High Sierra 10.13.4.
file_in_use = 'farsi_words'
def defaultFile(filename):
file_in_use = filename
return file_in_use
bN = Button(f0, text = 'Nouns', command =lambda: defaultFile('farsi_words'))
bN.pack(side='left')
bN.bind("<Button-1>",
bV = Button(f0, text = 'Verbs', command =lambda: defaultFile('farsi_verbs'))
bV.pack(side='left')
bA = Button(f0, text = 'Adjectives', command =lambda: defaultFile('farsi_adjectives'))
bA.pack(side='left')
bP = Button(f0, text = 'Prepositions', command =lambda: defaultFile('farsi_preps'))
bP.pack(side='left')
def commit(file_in_use):
word = e1.get()
definition = e2.get()
appendFile = open(file_in_use, 'a')#was this defined before def?
appendFile.write('\n' + word + ': ' + definition)
appendFile.close()
e1.delete(0, 'end')
e2.delete(0, 'end')
def review(file_in_use):
t1.delete('1.0', END)
readFile = open(file_in_use, 'r')
size = 0
splitList = []
for line in readFile:
splitWord = line.split(':')
splitWord = splitWord[0].strip('\n ')
splitList.append(splitWord)
size += 1
n = random.randint(0, size - 1)
t1.insert(INSERT, splitList[n] + '\n')
readFile.close()
def answer(file_in_use):
word = e3.get()
def1 = t1.get('1.0','end-1c')
def1 = def1.strip('\n')
readFile = open(file_in_use, 'r')
for line in readFile:
splitWord = line.split(': ')
if def1 == splitWord[0].strip('\n'):
if word == splitWord[1].strip('\n'):
t1.insert(INSERT, 'Good job!')
else:
t1.insert(INSERT, 'Not quite! Good try =)')
readFile.close()
def hint(file_in_use):
def1 = t1.get('1.0','2.0')
def1 = def1.strip('\n')
readFile = open(file_in_use, 'r')
for line in readFile:
splitWord = line.split(': ')
if def1 == splitWord[0].strip('\n'):
hint = splitWord[1]
hint1 = t1.get('2.0','end-1c')
lenHint1 = len(hint1)
if lenHint1 >= len(hint):
pass
else:
t1.insert(INSERT, hint[lenHint1])
print (hint1)
readFile.close()
You can pass arguments easily if you put your code in a class. Another thing is the tkinters function .after() you can try. I have made a simple GUI for demonstration of both.
import tkinter as tk
from tkinter import *
class GUI:
def __init__(self, master):
self.file_in_use = 'farsi_words'
self.master = master
self.bN = Button(master, text = 'Nouns', command = self.farsi_words)
self.bN.pack(side='left')
self.bN.bind("<Button-1>")
self.bV = Button(master, text = 'Verbs', command = self.farsi_verbs)
self.bV.pack(side='left')
self.bA = Button(master, text = 'Adjectives', command = self.farsi_adjectives)
self.bA.pack(side='left')
self.bP = Button(master, text = 'Prepositions', command = self.farsi_preps)
self.bP.pack(side='left')
def farsi_words(self, event=None):
self.file_in_use = 'Nouns'
self.master.after(1, self.commit)
def farsi_verbs(self, event=None):
self.file_in_use = 'Verbs'
self.master.after(1, self.commit)
def farsi_adjectives(self, event=None):
self.file_in_use = 'Adjectives'
self.master.after(1, self.commit)
def farsi_preps(self, event=None):
self.file_in_use = 'Prepositiones'
self.master.after(1, self.commit)
def commit(self, event=None):
print(self.file_in_use)
if __name__ == "__main__":
root = Tk()
my_gui = GUI(root)
root.mainloop()

Running a function when a widget window is brought to the front?

I'm building a gui front-end for a project I've been working on, and I'm having trouble figuring out this specific aspect of PyQT. Long ago there was a post that I had that I think would've solved the problem but I can't quite find it.
Regardless, I have the following files, main.py and playlistcreator.py respectively:
(main.py)
import getpass
import playlistcreator
import os
import sys
import sip
sip.setapi('QString', 2)
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
# Window class
class Window(QWidget):
def __init__(self): # constructor for Window (passes "self" -aka Window- to __init__ to initialize it)
super(Window, self).__init__() # inherits from QMainWindow
self.setGeometry(50, 50, 300, 150) # Set window dimensions
self.setWindowTitle("Google Music Playlist Transfer") # Set window title
self.setWindowIcon(QIcon('gmusic.png')) # Set window icon
self.login = QWidget() # login widget ("front page")
self.processing = QWidget() # on successful login - being processing data
self.file_inputs = QWidget() # after processing, ask user where they would like to store data
# call functions
self.loginUI()
self.processingUI()
self.file_inputsUI()
# create stacked widget and add layouts to stack
self.Stack = QStackedWidget(self)
self.Stack.addWidget(self.login)
self.Stack.addWidget(self.processing)
self.Stack.addWidget(self.file_inputs)
main_box = QHBoxLayout(self)
main_box.addWidget(self.Stack)
self.setLayout(main_box)
self.show()
def loginUI(self):
# Set email field
self.email = QLineEdit()
self.email.setMaxLength(110)
self.email.setAlignment(Qt.AlignLeft)
# Set password field
self.pwd = QLineEdit()
self.pwd.setAlignment(Qt.AlignLeft)
self.pwd.setEchoMode(QLineEdit.Password)
# Form layout
form_layout = QFormLayout()
form_layout.addRow("Email: ", self.email)
form_layout.addRow("Password: ", self.pwd)
# Login button
self.login_btn = QPushButton("Login", self) # login button
self.login_btn.clicked.connect(self.process_login) # tell button what to do
self.login_btn.resize(self.login_btn.sizeHint())
# Quit button
self.quit_btn = QPushButton("Exit", self) # exit button
self.quit_btn.clicked.connect(self.close_application) # tell button what to do
# Error label layout
self.error_layout = QHBoxLayout()
# Button box layout
button_box = QHBoxLayout()
button_box.addStretch(1)
button_box.addWidget(self.login_btn)
button_box.addWidget(self.quit_btn)
# input layout (main layout for "home")
input_box = QVBoxLayout()
input_box.addLayout(self.error_layout)
input_box.addLayout(form_layout)
input_box.addLayout(button_box)
self.login.setLayout(input_box)
def processingUI(self):
# setup layout
layout = QHBoxLayout()
# alert user that we're grabbing track data
self.progress_label = QLabel("Grabbing tracks from Google Music. . .")
self.progress_label.setStyleSheet("color: rgb(0, 100, 0);")
layout.addWidget(self.progress_label)
# Get users list of "thumbs up" tracks from Google Music
# set layout
favorite_tracks = self.get_tracks
self.processing.setLayout(layout)
def file_inputsUI(self):
layout = QFormLayout()
# Set text field for directory
self.dir_textbox = QTextEdit(self)
# Add textbox to layout
layout.addRow("Music Directory: ", self.dir_textbox)
self.file_inputs.setLayout(layout)
def close_application(self):
confirm = QMessageBox.question(self, 'Exit Confirmation',
"Are you sure you want to exit?",
QMessageBox.Yes | QMessageBox.No)
if confirm == QMessageBox.Yes:
sys.exit()
else:
pass
def process_login(self):
email_input = str(self.email.text())
pwd_input = str(self.pwd.text())
login_successful = playlistcreator.login(email_input, pwd_input)
if login_successful:
self.Stack.setCurrentIndex(1)
else:
self.error_label = QLabel("Please check your email/password!")
self.error_label.setStyleSheet("color: rgb(255, 0, 0);")
self.error_layout.addWidget(self.error_label)
def get_tracks(self):
tracks = playlistcreator.get_favorite_tracks()
print("You have ", len(tracks), " favorite tracks!")
return tracks
# def open_dir_dialog(self):
# directory = QFileDialog.getExistingDirectory(self, 'Select USB Drive Location')
# self.myTextBox.setText(fileName)
def main():
# Create an PyQT5 application object.
app = QApplication(sys.argv)
GUI = Window()
sys.exit(app.exec_())
# # Input Music Directory
# music_dir = input("Please put the path to your music folder: ")
# list_of_paths = playlistcreator.findmp3(music_dir, favorite_tracks)
# # Input playlist file save location
# playlist_path = input("Where would you like to save the playlist?: ")
# playlist_name = input("What would you like to name the playlist? ")
# playlist_name += ".m3u8"
# # Testing appending file extension to string
# playlistcreator.addtoplaylist(list_of_paths, playlist_path, playlist_name)
# playlistcreator.logout()
main()
(playlistcreator.py)
import os
from gmusicapi import Mobileclient
from mutagen.easyid3 import EasyID3
api = Mobileclient()
songCount = 0
favorite_files_path = []
logged_in = False
def login(email, password):
library = []
if "#" not in email:
email += "#gmail.com"
logged_in = api.login(email, password, Mobileclient.FROM_MAC_ADDRESS)
return logged_in
def get_favorite_tracks():
print("Getting songs from Google Music. . .")
library = api.get_all_songs()
print("There are", len(library), "items in your music library")
good_songs = [song for song in library if song['rating'] == '5']
print("You have", len(good_songs), "favorite tracks!")
return good_songs
def logout():
api.logout()
def findmp3(rootFolder, favoriteTracks):
print("Searching for favorite tracks. . .")
for directory, subdirectory, files in os.walk(rootFolder, topdown=False): # for all files in directory
global songCount
global favorite_files_path
for mp3 in files: # for files in
if mp3.endswith(".mp3"): # if file ends with .mp3
file_path = os.path.join(directory, mp3) # concatenate to create full path
try:
file_tags = EasyID3(file_path) # grab file tags from mp3 file
except:
file_tags = EasyID3() # create tags if none are found
file_tags.save(file_path) # save file to have new tags
if "title" in file_tags:
fileTitle = file_tags["title"][0] # TIT2 = corresponding tag in mutagen for song title
else:
fileTitle = "None"
if "artist" in file_tags:
fileArtist = file_tags["artist"][0] # TPE = corresponding tag in mutagen for artist
else:
fileArtist = "None"
if "album" in file_tags:
fileAlbum = file_tags["album"][0] # TALB = corresponding tag in mutagen for album
else:
fileAlbum = "None"
for track in favoriteTracks:
gMusicTitle = track["title"]
gMusicArtist = track["artist"]
gMusicAlbum = track["album"]
if fileTitle in gMusicTitle and fileArtist in gMusicArtist and fileAlbum in gMusicAlbum: # if file tags (artist, album, title) match gMusic tags
songCount += 1
if songCount == 1:
print("Found 1 song")
else:
print("Found", songCount, "songs") # print updated count of found tracks
favorite_files_path.append(file_path) # add all found files to a list (via their paths)
break # break out of "for track in favorite tracks"
return favorite_files_path
def addtoplaylist(paths, playlist_path, playlist_name):
# Open file (or create if it does not exist)
# change to given directory
try:
os.chdir(playlist_path)
except Exception as err:
print(err)
# open file - if it does not exist, create it
with open(playlist_name, 'a+', encoding="UTF-8") as playlistFile:
print("Adding tracks...", end="")
for track in paths:
print(".", end="")
playlistFile.write(track + '\n')
playlistFile.close()
The problem I've been running into is when the user logs in they hit the processingUI window (which states that the program is grabbing all their tracks from Google) but it doesn't actually seem to be running the get_tracks() method (which is what actually gets the user's tracks from Google), as the program hangs there and doesn't do anything.
I've tested the program without a GUI using straight command line, and it works flawlessly, but I'm not sure what the issue is with the GUI - do I need to thread the execution to start when the proper "window" is brought to the front?

How do I insert data from file in the first column of a qtablewidget or qtableview?

I would like to insert a list of users from a file into the first row of a tablewidget or tableview. I am currently trying it out with a tablewidget. So far, the code below is what I came up with after having seen the answer from this post. Basically if you look at the image, I'm trying to do exactly that then later I'll add an ok button to perform the actions.
from PyQt4 import QtGui, QtCore
class Window(QtGui.QWidget):
def __init__(self, rows, columns):
QtGui.QWidget.__init__(self)
self.table = QtGui.QTableWidget(rows, columns, self)
self.table.setHorizontalHeaderItem(0, QtGui.QTableWidgetItem("Users"))
self.table.setHorizontalHeaderItem(1, QtGui.QTableWidgetItem("Delete User"))
self.table.setHorizontalHeaderItem(2, QtGui.QTableWidgetItem("Delete User and Home"))
self.table.verticalHeader().hide()
header = self.table.horizontalHeader()
header.setStretchLastSection(True)
for column in range(columns):
if column == 0:
with open("users") as input:
if input is not None:
users = input.readlines()
for line in users:
users = QtGui.QTableWidgetItem(line)
print line
input.close()
for row in range(rows):
if column % 3:
item = QtGui.QTableWidgetItem('%d' % column)
item.setFlags(QtCore.Qt.ItemIsUserCheckable |
QtCore.Qt.ItemIsEnabled)
item.setCheckState(QtCore.Qt.Unchecked)
self.table.setItem(row, column, item)
self.table.itemClicked.connect(self.handleItemClicked)
layout = QtGui.QVBoxLayout(self)
layout.addWidget(self.table)
self._list = []
def handleItemClicked(self, item):
if item.checkState() == QtCore.Qt.Checked:
print('"%s" Checked' % item.text())
self._list.append(item.row())
print(self._list)
else:
print('"%s" Clicked' % item.text())
if __name__ == '__main__':
import sys
app = QtGui.QApplication(sys.argv)
window = Window(6, 3)
window.resize(400, 400)
window.show()
sys.exit(app.exec_())
#How do I insert data from file in the first column of a qtablewidget or qtableview?
#This is the example code for insert data to Qtablewidget
#Please not the print result. I hope you can understand how to use columns and row values.
#I used the input data from "dictionary variable - self.input". You can replace this input variable to your input data.
#if any doubts regarding this below code, please let me know.
#If your are not expecting this answer, sorry.
#Thanks, Subin
import sys
from PyQt4 import QtGui
from PyQt4 import QtCore
class Window (QtGui.QWidget):
def __init__(self, parent=None):
super(Window, self).__init__(parent)
#Read user text file and append to dictionary variable
userDataPath = 'C:/Users/Subin/Desktop/userList.txt'
readUserData = open (userDataPath, 'r')
userList = readUserData.readlines ()
#self.input = {'bruno':[0,1], 'shelly':[0,0], 'nobody':[1,1]}
self.input = {}
for eachUser in userList :
if eachUser.strip() :
self.input.setdefault (eachUser.strip(), [1, 1])
self.rows = 3
self.columns = len(self.input)
self.tableWidget = QtGui.QTableWidget (self)
self.tableWidget.setGeometry (QtCore.QRect(10, 10, 500, 180))
self.tableWidget.setObjectName ('tableWidget')
self.tableWidget.setColumnCount(self.rows)
self.tableWidget.setRowCount(self.columns)
print '\t\tcolumns rows\n'
cLoop = 0
for eachInput in self.input :
self.item_name = QtGui.QTableWidgetItem ()
self.tableWidget.setItem (cLoop, 0, self.item_name)
self.item_name.setText (eachInput)
print 'name\t\tcolumns ', cLoop, ' rows ', 0
rLoop = 0
for eachAttri in self.input[eachInput] :
self.item_attri = QtGui.QTableWidgetItem ()
self.tableWidget.setItem (cLoop, rLoop+1, self.item_attri)
self.item_attri.setFlags (QtCore.Qt.ItemIsUserCheckable|QtCore.Qt.ItemIsEnabled)
self.item_attri.setCheckState (QtCore.Qt.Unchecked)
if eachAttri==1 :
self.item_attri.setCheckState (QtCore.Qt.Checked)
print 'attributes\tcolumns ', cLoop, ' rows ', rLoop+1
rLoop+=1
cLoop+=1
print '\n'
if __name__=='__main__':
app = QtGui.QApplication(sys.argv)
wind = Window ()
wind.show()
sys.exit(app.exec_())
The following code may do what you need. It assumes that you have a file users.txt, which consists of one name per row, like
Harry
Sally
Wang
Jon
Leona
You then need to read that file and get rid of the line break character.
from PyQt4 import QtGui, QtCore
class Window(QtGui.QWidget):
def __init__(self):
QtGui.QWidget.__init__(self)
with open("users.txt") as f:
users = f.readlines()
users = [user.split("\n")[0] for user in users]
self.table = QtGui.QTableWidget(len(users), 2, self)
self.table.setHorizontalHeaderLabels(["Delete User", "Delete Home"])
self.table.setVerticalHeaderLabels(users)
for column in range(2):
for row in range(len(users)):
item = QtGui.QTableWidgetItem("")
item.setFlags(QtCore.Qt.ItemIsUserCheckable |
QtCore.Qt.ItemIsEnabled)
item.setCheckState(QtCore.Qt.Unchecked)
self.table.setItem(row, column, item)
self.table.itemClicked.connect(self.handleItemClicked)
layout = QtGui.QVBoxLayout(self)
layout.addWidget(self.table)
self._list = []
def handleItemClicked(self, item):
if item.checkState() == QtCore.Qt.Checked:
print('"%s" Checked' % item.text())
self._list.append(item.row())
print(self._list)
else:
print('"%s" Clicked' % item.text())
if __name__ == '__main__':
import sys
app = QtGui.QApplication(sys.argv)
window = Window()
window.resize(350, 300)
window.show()
sys.exit(app.exec_())

How can I find a substring and highlight it in QTextEdit?

I have a QTextEdit window that shows the content of a file.
I would like to be able to find all matches inside the text using a regex and highlight them either by making the match background different or by changing the match text color or making it bold. How can I do this?
I think the simplest solution to your problem is to use the cursor associated to your editor in order to do the formatting. This way you can set the foreground, the background, the font style... The following example marks the matches with a different background.
from PyQt4 import QtGui
from PyQt4 import QtCore
class MyHighlighter(QtGui.QTextEdit):
def __init__(self, parent=None):
super(MyHighlighter, self).__init__(parent)
# Setup the text editor
text = """In this text I want to highlight this word and only this word.\n""" +\
"""Any other word shouldn't be highlighted"""
self.setText(text)
cursor = self.textCursor()
# Setup the desired format for matches
format = QtGui.QTextCharFormat()
format.setBackground(QtGui.QBrush(QtGui.QColor("red")))
# Setup the regex engine
pattern = "word"
regex = QtCore.QRegExp(pattern)
# Process the displayed document
pos = 0
index = regex.indexIn(self.toPlainText(), pos)
while (index != -1):
# Select the matched text and apply the desired format
cursor.setPosition(index)
cursor.movePosition(QtGui.QTextCursor.EndOfWord, 1)
cursor.mergeCharFormat(format)
# Move to the next match
pos = index + regex.matchedLength()
index = regex.indexIn(self.toPlainText(), pos)
if __name__ == "__main__":
import sys
a = QtGui.QApplication(sys.argv)
t = MyHighlighter()
t.show()
sys.exit(a.exec_())
The code is self-explanatory but if you have any questions just ask them.
Here is a sample of how can you highlight text in a QTextEdit:
#!/usr/bin/env python
#-*- coding:utf-8 -*-
from PyQt4.QtGui import *
from PyQt4.QtCore import *
class highlightSyntax(QSyntaxHighlighter):
def __init__(self, listKeywords, parent=None):
super(highlightSyntax, self).__init__(parent)
brush = QBrush(Qt.darkBlue, Qt.SolidPattern)
keyword = QTextCharFormat()
keyword.setForeground(brush)
keyword.setFontWeight(QFont.Bold)
self.highlightingRules = [ highlightRule(QRegExp("\\b" + key + "\\b"), keyword)
for key in listKeywords
]
def highlightBlock(self, text):
for rule in self.highlightingRules:
expression = QRegExp(rule.pattern)
index = expression.indexIn(text)
while index >= 0:
length = expression.matchedLength()
self.setFormat(index, length, rule.format)
index = text.indexOf(expression, index + length)
self.setCurrentBlockState(0)
class highlightRule(object):
def __init__(self, pattern, format):
self.pattern = pattern
self.format = format
class highlightTextEdit(QTextEdit):
def __init__(self, fileInput, listKeywords, parent=None):
super(highlightTextEdit, self).__init__(parent)
highlightSyntax(QStringList(listKeywords), self)
with open(fileInput, "r") as fInput:
self.setPlainText(fInput.read())
if __name__ == "__main__":
import sys
app = QApplication(sys.argv)
main = highlightTextEdit("/path/to/file", ["foo", "bar", "baz"])
main.show()
sys.exit(app.exec_())
QT5 has updated the RegEx, see QRegularExpression https://dangelog.wordpress.com/2012/04/07/qregularexpression/
I have updated the first example using cursors.
Note the following changes:
This doesn't wrap an edit, but uses the edit box inside, it could easily be changed to allow you to pass in the edit widget.
This does a proper regex find, not just a single word.
def do_find_highlight(self, pattern):
cursor = self.editor.textCursor()
# Setup the desired format for matches
format = QTextCharFormat()
format.setBackground(QBrush(QColor("red")))
# Setup the regex engine
re = QRegularExpression(pattern)
i = re.globalMatch(self.editor.toPlainText()) # QRegularExpressionMatchIterator
# iterate through all the matches and highlight
while i.hasNext():
match = i.next() #QRegularExpressionMatch
# Select the matched text and apply the desired format
cursor.setPosition(match.capturedStart(), QTextCursor.MoveAnchor)
cursor.setPosition(match.capturedEnd(), QTextCursor.KeepAnchor)
cursor.mergeCharFormat(format)

Categories

Resources