Pyqt5 how to set URL and show the page - python

I am studing python and making bookmark function for practice purpose.
Now I could register url to tab menu.
and when I press the link from tab menu. nothing shows on browser.
following area, somebody please le me know what is wrong.
"self.browser.setUrl(QUrl(action_url))"
text itself(action_url) looks OK, but browser does not show.
entire code is this.
import os
import sys
from PyQt5.QtCore import QSize, Qt, QUrl
from PyQt5.QtGui import QIcon, QPixmap
from PyQt5.QtWebEngineWidgets import QWebEngineView
from PyQt5.QtWidgets import (
QAction,
QApplication,
QDialog,
QDialogButtonBox,
QFileDialog,
QLabel,
QLineEdit,
QMainWindow,
QToolBar,
QVBoxLayout,
)
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.browser = QWebEngineView()
self.browser.setUrl(QUrl("http://google.com"))
self.setCentralWidget(self.browser)
# tag::navigation1[]
navtb = QToolBar("Navigation")
navtb.setIconSize(QSize(16, 16))
self.addToolBar(navtb)
#bookmark button
bookmark_btn = QAction(QIcon(os.path.join("icons", "smiley.png")), "Bookmark", self)
bookmark_btn.setStatusTip("add to bookmark")
bookmark_btn.triggered.connect(self.add_bookmark)
navtb.addAction(bookmark_btn)
navtb.addSeparator()
# tag::menuBookmark[]
self.bookmark_menu = self.menuBar().addMenu("&Bookmark")
bookmark_select_action = QAction("http://google.com",self)
bookmark_select_action.triggered.connect(self.navigate_bookmark)
self.bookmark_menu.addAction(bookmark_select_action)
self.show()
# tag::bookmark[]
def add_bookmark(self):
bookmark_title = self.browser.page().title()
bookmark_url = self.browser.url().toString()
bookmark_select_action = QAction(bookmark_url,self)
bookmark_select_action.triggered.connect(self.navigate_bookmark)
self.bookmark_menu.addAction(bookmark_select_action)
# tag::navigationBookmark[]
def navigate_bookmark(self):
action = self.sender()
action_url = '"'+action.text()+'"'
self.browser.setUrl(QUrl(action_url)) #this code does not function as I expected
print(action_url)
app = QApplication(sys.argv)
app.setApplicationName("Mozzarella Ashbadger")
app.setOrganizationName("Mozzarella")
app.setOrganizationDomain("mozzarella.org")
window = MainWindow()
app.exec_()

I don't understand why you put the text inside the quotation marks. In general if you have a string and you want to convert it to QUrl use QUrl::fromUserInput(), also use the load() method:
def navigate_bookmark(self):
action = self.sender()
url = QUrl.fromUserInput(action.text())
self.browser.load(url)
Another strategy is to save the QUrl in the QAction and then retrieve it:
def add_bookmark(self):
bookmark_title = self.browser.page().title()
bookmark_url = self.browser.url()
bookmark_select_action = QAction(bookmark_url.toString(), self)
bookmark_select_action.setData(bookmark_url)
# or
# bookmark_select_action.setProperty("url", bookmark_url)
bookmark_select_action.triggered.connect(self.navigate_bookmark)
self.bookmark_menu.addAction(bookmark_select_action)
def navigate_bookmark(self):
action = self.sender()
url = action.data()
# or
# url = action.property("url")
self.browser.load(url)

Related

pyqt5 problem. I am having trouble with classes. When I call the function it doesn't do anything at all

##imports
from PyQt5.QtWidgets import (QWidget, QPushButton, QLineEdit, QInputDialog, QApplication, QLabel,QMainWindow,)
from PyQt5.QtWidgets import QLineEdit
from PyQt5.QtGui import *
import sys
#defining class
class UI:
#basic window
def window(self,app,window,size,title,show,):
self.app = QApplication(sys.argv)
self.win = QMainWindow()
self.win.setGeometry(200,200,600,600)
self.win.setWindowTitle("Calculator App ")
self.win.show()
sys.exit(app.exec_())
#text that will show the functions of the calculator
def modes_header(self,type,text,pos,font):
self.functions_type = QLabel(win)
self.functions_text.setText("Modes")
self.functions_pos.move(10, 400)
self.functions_font.setFont(QFont('Constantinus',21))
#this will be the multiplication function
def multiply_button(self,label,text,pos,font):
self.multButton_type = QLabel(win)
self.multButton_text.setText("Multiply")
self.multButton_pos.move(10,450)
self.multButton_font("Arial",19)
#Calling Functions
ui = UI
win = ui.window
ui.window()
ui.modes_header()
ui.multiply_button()

Indexing PyQt5 combobox when using QFileSystemModel

I need to select the default file that appears in a combobox from a directory listing of files. With a normal combobox, it is easy enough to find the index of the value you want using .findText, but this does not appear to work for QFileSystemModel comboboxes, possibly due to the way the list of options does not populate until the directory listing can be resourced.
Here is what I have tried:
import sys
import collections
from PyQt5 import QtCore, QtWidgets
from PyQt5.QtWidgets import QMainWindow, QLabel, QGridLayout, QWidget, QComboBox
from PyQt5.QtCore import QSize, QRect
class ComboWindow(QMainWindow):
def __init__(self):
QMainWindow.__init__(self)
self.setMinimumSize(QSize(640, 140))
self.setWindowTitle("Combobox example")
centralWidget = QWidget(self)
self.setCentralWidget(centralWidget)
# Create combobox and add items.
self.fsm = QtWidgets.QFileSystemModel()
self.fsm.setNameFilters(["*.txt"])
self.configComboBox = QtWidgets.QComboBox(self)
self.configComboBox.setGeometry(QRect(40, 40, 491, 31))
self.configComboBox.setObjectName(("comboBox"))
self.configComboBox.setModel(self.fsm)
self.fsm.setFilter(QtCore.QDir.NoDotAndDotDot | QtCore.QDir.Files)
# "text_files" is a subdir of current dir with files
# example1.txt, example2.txt, example3.txt
self.configComboBox.setRootModelIndex(self.fsm.setRootPath("text_files"))
# V V This section does not work V V
index = self.configComboBox.findText(MainConfig.settings["default_txt_file"])
self.configComboBox.setCurrentIndex(index)
class MainConfig:
settings = collections.OrderedDict()
#staticmethod
def createDefaultConfig(name):
MainConfig.settings["default_txt_file"] = "example3.txt"
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
mainWin = ComboWindow()
mainWin.show()
sys.exit( app.exec_() )
As I indicated in this answer, the QFileSystemModel is loaded asynchronously in a new thread so you must use the directoryLoaded signal to know when the information is finished loading:
import collections
import os
import sys
from PyQt5.QtWidgets import (
QApplication,
QComboBox,
QFileSystemModel,
QMainWindow,
QWidget,
)
from PyQt5.QtCore import pyqtSlot, QDir, QRect, QSize
class ComboWindow(QMainWindow):
def __init__(self, parent=None):
super(ComboWindow, self).__init__(parent=None)
self.setMinimumSize(QSize(640, 140))
self.setWindowTitle("Combobox example")
centralWidget = QWidget(self)
self.setCentralWidget(centralWidget)
# Create combobox and add items.
self.fsm = QFileSystemModel()
self.fsm.setNameFilters(["*.txt"])
self.configComboBox = QComboBox(self)
self.configComboBox.setGeometry(QRect(40, 40, 491, 31))
self.configComboBox.setObjectName(("comboBox"))
self.configComboBox.setModel(self.fsm)
self.fsm.setFilter(QDir.NoDotAndDotDot | QDir.Files)
self.fsm.directoryLoaded.connect(self.on_directoryLoaded)
current_dir = os.path.dirname(os.path.realpath(__file__))
dir_path = os.path.join(current_dir, "text_files")
self.configComboBox.setRootModelIndex(self.fsm.setRootPath(dir_path))
#pyqtSlot(str)
def on_directoryLoaded(self, path):
index = self.configComboBox.findText(MainConfig.settings["default_txt_file"])
self.configComboBox.setCurrentIndex(index)
class MainConfig:
settings = collections.OrderedDict()
#staticmethod
def createDefaultConfig(name):
MainConfig.settings["default_txt_file"] = name
if __name__ == "__main__":
MainConfig.createDefaultConfig("example3.txt")
app = QApplication(sys.argv)
mainWin = ComboWindow()
mainWin.show()
sys.exit(app.exec_())

Costum QSortFilterProxyModel

Hello python community
I'm trying to apply a QStandardItemModel on a QTableView according to the text from QLineEdid, of course i've found documentation and it works great on latins letters, but in may case, data is arabic.
let d be a data from my table, and t the text from editline, i have to apply a function on both d and t before comparing them with RegExp (a function from PyArabic) and I don't know how to do that.
I hope to find help here
Thank you!!
here is my code
import sys
from PyQt5.QtCore import Qt, QSortFilterProxyModel, QRegExp
from PyQt5.QtGui import QStandardItemModel, QStandardItem
from PyQt5.QtWidgets import QWidget, QLineEdit, QTableView, QVBoxLayout, QApplication
from pyarabic.araby import strip_tashkeel
class MyWindow(QWidget):
def __init__(self):
super(QWidget, self).__init__()
word_edit = QLineEdit()
word_edit.setLayoutDirection(Qt.RightToLeft)
word_edit.textChanged.connect(self.word_edit_text_changed)
model = QStandardItemModel()
model.setHorizontalHeaderLabels(['الكلمة', 'الطبيعة', 'الحالة'])
model.appendRow([QStandardItem('ذَهبَ'), QStandardItem('فعل'), QStandardItem('غير مراقب')])
model.appendRow([QStandardItem('ذُهبٌ'), QStandardItem('اسم'), QStandardItem('مراقب')])
model.appendRow([QStandardItem('مَذهب'), QStandardItem('اسم'), QStandardItem('مراقب')])
self.filter = QSortFilterProxyModel()
self.filter.setSourceModel(model)
self.filter.setFilterKeyColumn(0)
words_table = QTableView()
words_table.setLayoutDirection(Qt.RightToLeft)
words_table.setModel(self.filter)
v_layout = QVBoxLayout()
v_layout.addWidget(word_edit)
v_layout.addWidget(words_table)
self.setLayout(v_layout)
def word_edit_text_changed(self, text):
# let d be an the date from the model
# i need to compare strip_tashkeel(text) to strip_tashkeel(d)
search = QRegExp(strip_tashkeel(text), Qt.CaseInsensitive)
self.filter.setFilterRegExp(search)
if __name__ == '__main__':
app = QApplication(sys.argv)
w = MyWindow()
w.show()
sys.exit(app.exec_())

QScrollArea does not attach to label

I am trying to display an image label with scrollbars within a Box layout.
However, the scroll area appears at the wrong place with the wrong size.
Could you please tell me what I am doing wrong?
import sys
from PyQt5 import QtCore
from PyQt5.QtWidgets import QApplication, QMainWindow, QVBoxLayout, QWidget, QPushButton, QLabel, QScrollArea
from PyQt5.QtGui import QPixmap
class ApplicationWindow(QMainWindow):
def __init__(self):
QMainWindow.__init__(self)
main_widget = QWidget(self)
btn = QPushButton("Bye", self)
btn.clicked.connect(self.close)
img = QPixmap("1.jpg")
label = QLabel(main_widget)
label.setPixmap(img)
scrollArea = QScrollArea(main_widget)
scrollArea.setWidgetResizable(True)
scrollArea.setWidget(label)
l = QVBoxLayout(main_widget)
l.addWidget(label)
l.addWidget(btn)
self.setCentralWidget(main_widget)
def closeEvent(self, ce):
self.close()
if __name__ == '__main__':
app = QApplication(sys.argv)
aw = ApplicationWindow()
aw.show()
app.exec_()
The result is:
The problem is that instead of adding the QLabel to QVBoxLayout you must add the QScrollArea. You must change:
l.addWidget(label)
to
l.addWidget(scrollArea)

progressbar in Qlineedit

I am migrating some code from pyGObject to pyQT4 and I make use of set_progress_fraction as a means to indication the percentage of the MAXIMUM the inputted value is.
I am trying to find an equivalent in pyQT4 but I am failing.
QLineEdit does have a paint method so is the only real way to "paint" the LineEdit?
--edit--
example of the gtk equiv:
& snippit of my present pyGObject code
def on_entry_change(self,widget,*args):
try:
tmp = float(widget.get_text())
tmp = (tmp- widget.min_bin)/(widget.max_bin - widget.min_bin)
widget.set_progress_fraction(tmp)
except:
return
I think you want to connect the value in the QLineEdit to a method that modifies the progress bar. This might help:
from __future__ import division
import sys
from PyQt4.QtCore import (Qt, SIGNAL)
from PyQt4.QtGui import (QApplication, QDialog, QLineEdit,
QVBoxLayout, QProgressBar, QWidget, QLabel)
class Form(QWidget):
def __init__(self, parent=None):
super(Form, self).__init__(parent)
self.barA = QProgressBar()
self.maximum = 200
self.label1 = QLabel('Maximum = 200')
self.seqM = QLineEdit("num")
layoutO = QVBoxLayout() #set overal layout
layoutO.addWidget(self.label1)
layoutO.addWidget(self.barA)
layoutO.addWidget(self.seqM)
self.setLayout(layoutO)
self.connect(self.seqM, SIGNAL("returnPressed()"), self.updatebar)
def updatebar(self):
try:
currval = float(self.seqM.text())
except:
print 'enter float or integer only'
self.track = (currval/self.maximum)*100
self.barA.setValue(self.track)
app = QApplication(sys.argv)
form = Form()
form.show()
app.exec_()`

Categories

Resources