Qwebview with threading in python qt - python-2.7

I want to run multiple QWebview using multi-threading for scrape data. But have no idea about how to implement thread using qwebview. Here I have write some code:
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.QtWebKit import *
from PyQt4.QtNetwork import *
from PyQt4 import QtCore, QtGui
from lxml import etree,html
from PyQt4.QtCore import Qt
import sys
class Form(QWidget):
def __init__(self, parent=None):
super(Form, self).__init__(parent)
self.setMouseTracking(True)
vbox = QVBoxLayout()
self.browser = QWebView()
self.browser.connect(self.browser,SIGNAL('loadFinished(bool)'),self.loadFinished)
#vbox.addWidget(self.browser)
self.browser.load(QtCore.QUrl("http://www.google.com"))
self.browser_tabs = QTabWidget()
self.browser_tabs.setTabPosition(QTabWidget.South)
b1_tab = QWidget()
d = QHBoxLayout()
d.addWidget(self.browser)
b1_tab.setLayout(d)
self.browser_tabs.addTab(b1_tab,"browser0")
vbox.addWidget(self.browser_tabs)
self.setLayout(vbox)
def loadFinished(self,ok):
print ok
def main():
app = QApplication(sys.argv)
ex = Form()
ex.show()
ex.setGeometry(150, 100, 1024, 770)
#ex.showMaximized()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
You can use tab widget for open multiple browser.

Define a new function for your Form class. And use thread.start_new_thread(function_name, arguments()).
import thread
class Form(QWidget):
...
def addNewTab(self, newUrl, tabIndex):
new_browser = QWebView()
new_browser.connect(self.browser,SIGNAL('loadFinished(bool)'),self.loadFinished)
new_browser.load(QtCore.QUrl(newUrl))
new_tab = QWidget()
d = QHBoxLayout()
d.addWidget(new_browser)
new_tab.setLayout(d)
self.browser_tabs.addTab(new_tab, "browser" + str(tabIndex))
# Do your scraping here
def main():
app = QApplication(sys.argv)
ex = Form()
ex.show()
ex.setGeometry(150, 100, 1024, 770)
thread.start_newThread(ex.addNewTab, (someUrl1, 1))
thread.start_newThread(ex.addNewTab, (someUrl2, 2))
thread.start_newThread(ex.addNewTab, (someUrl3, 3))
sys.exit(app.exec())

Related

Using the keyboard print data

I have a problem with python 2.7.
Question: When I use the zoom function, I can not use the "keyboard" to print my real data. Here, I add the keyboard event in my code.
How do I exist in both functions? How should I debug the code?
import matplotlib
import sys
import random
matplotlib.use("Qt5Agg")
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar
from matplotlib.figure import Figure
import matplotlib.pyplot as plt
import numpy as np
from PyQt5.QtCore import *
import re
class MyMplCanvas(FigureCanvas):
def __init__(self, parent=None, width=10, height=4, dpi=100):
FigureCanvas.__init__(self, Figure(figsize=(width, height), dpi=dpi))
self.setParent(parent)
FigureCanvas.setSizePolicy(self, QSizePolicy.Expanding, QSizePolicy.Expanding)
FigureCanvas.updateGeometry(self)
self.axes = self.figure.add_subplot(211)
self.mpl_connect("motion_notify_event", self.on_move)
self.po_annotation = []
self.ff=[]
def start_static_plot(self):
for i in range(0, 990):
(point,) = self.axes.plot(x, y, "-o")
annotation = self.axes.annotate(
("x=" + str(x), "y=" + str(y)),
textcoords="data",
horizontalalignment="left",
arrowprops=dict(arrowstyle="simple",connectionstyle="arc3,rad=+0.2"), bbox=dict(boxstyle="round", facecolor="w", edgecolor="0.1", alpha=0.9)
annotation.set_visible(False)
self.po_annotation.append([point, annotation])
self.axes.set_xlim(-0.5, 1000)
self.axes.set_ylim(-5, 9.5 ** 2)
def on_move(self, event):
visibility_changed = Ture
for point, annotation in self.po_annotation:
should_be_visible = point.contains(event)[4]
if should_be_visible != annotation.get_visible():
visibility_changed = True
annotation.set_visible(should_be_visible)
datachouse=str(annotation)
self.ff = np.loadtxt(f)
if visibility_changed:
self.draw()
def mouseReleaseEvent(self, event):
if(event.button() == Qt.LeftButton):
def initUi(self):
self.mpl.start_static_plot()
self.layout.addWidget(self.mpl)
if __name__ == '__main__':
app = QApplication(sys.argv)
sys.exit(app.exec_())
If you don't want to remove the default behavior of a method then you must invoke the parent method:
def mouseReleaseEvent(self, event):
super(MyMplCanvas, self).mouseReleaseEvent(event)
if event.button() == Qt.LeftButton:
print("result=", self.ff)

How to get the selection item in list view using pyqt4

Here is my sample code. When I click the index item in list view, I am getting the selection item,it's working fine.But I want to get the selected item using up and down arrows. Can anyone please help me. Thank you in advance.
Given below is my code:
import sys
from PyQt4 import QtCore,QtGui
class mtable(QtGui.QMainWindow):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.auto_search1 = QtGui.QWidget()
self.auto_search_vbox1 = QtGui.QVBoxLayout(self.auto_search1)
self.auto_search_vbox1.setAlignment(QtCore.Qt.AlignLeft)
hbox1=QtGui.QHBoxLayout()
self.le_search1 = QtGui.QLineEdit()
self.se_btn1 = QtGui.QPushButton("Search")
self.searchBtn = QtGui.QPushButton("Close")
self.searchBtn.clicked.connect(self.auto_search1.close)
self.se_btn1.clicked.connect(self.filterClicked1)
hbox1.addWidget(self.le_search1)
hbox1.addWidget(self.se_btn1)
hbox1.addWidget(self.searchBtn)
self.auto_search_vbox1.addLayout(hbox1)
self.total_list1 =[]
self.list1 = QtGui.QListView()
self.list1.clicked.connect(self.on_treeView_clicked)
self.model1 = QtGui.QStandardItemModel(self.list1)
self.y =['one','two', 'three']
for i in self.y:
self.total_list1.append(i)
for code in self.total_list1:
item1 = QtGui.QStandardItem(code)
self.model1.appendRow(item1)
self.list1.setModel(self.model1)
self.auto_search_vbox1.addWidget(self.list1)
self.auto_search1.show()
self.auto_search1.resize(1000,500)
#QtCore.pyqtSlot(QtCore.QModelIndex)
def on_treeView_clicked(self, index):
itms = self.list1.selectedIndexes()
for data in itms:
print index.data().toString()
self.le_search1.setText(index.data().toString())
self.filterClicked1()
def filterClicked1(self):
print "searching logic"
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
tb = mtable()
sys.exit(app.exec_())
Here I need to select the green highlighted item using arrow keys without clicking the item
You have to use the currentChanged signal of the selectionModel() of the QListView:
import sys
from PyQt4 import QtCore,QtGui
class MainWindow(QtGui.QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.lineedit = QtGui.QLineEdit()
self.search_button = QtGui.QPushButton("Search")
self.close_button = QtGui.QPushButton("Close")
self.listview = QtGui.QListView()
model = QtGui.QStandardItemModel(self.listview)
for e in ('one', 'two', 'three'):
model.appendRow(QtGui.QStandardItem(e))
self.listview.setModel(model)
# signals connections
self.listview.selectionModel().currentChanged.connect(self.on_currentChanged)
QtCore.QTimer.singleShot(0, self.selectFirstItem)
# layout
central_widget = QtGui.QWidget()
self.setCentralWidget(central_widget)
vlay = QtGui.QVBoxLayout(central_widget)
hlay = QtGui.QHBoxLayout()
hlay.addWidget(self.lineedit)
hlay.addWidget(self.search_button)
hlay.addWidget(self.close_button)
vlay.addLayout(hlay)
vlay.addWidget(self.listview)
self.resize(640, 480)
def selectFirstItem(self):
self.listview.setFocus()
ix = self.listview.model().index(0, 0)
self.listview.selectionModel().setCurrentIndex(ix, QtGui.QItemSelectionModel.Select)
#QtCore.pyqtSlot(QtCore.QModelIndex)
def on_currentChanged(self, current):
self.lineedit.setText(current.data())
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
w = MainWindow()
w.show()
sys.exit(app.exec_())

How to search an item in list widget using with pyqt4

Here in my sample program,I want to display the lot of names in list widget.In that, I want to search a particular item in list widget using search button,and I want to print that item name in list widget.
Given below is my code:
import sys
from PyQt4 import QtGui, QtCore
class Example(QtGui.QWidget):
def __init__(self):
super(Example, self).__init__()
self.initUI()
def initUI(self):
auto_search_vbox = QtGui.QVBoxLayout(self)
hbox=QtGui.QHBoxLayout()
le_search = QtGui.QLineEdit()
se_btn = QtGui.QPushButton("Search")
se_btn.clicked.connect(self.find_item)
hbox.addWidget(le_search)
hbox.addWidget(se_btn)
auto_search_vbox.addLayout(hbox)
self.listwidget = QtGui.QListWidget()
self.total_list =["machine","printer","xerox bundles"]
self.listwidget.addItems(self.total_list)
auto_search_vbox.addWidget(self.listwidget)
self.show()
def find_item(self):
out = self.listwidget.findItems("mac", QtCore.Qt.MatchExactly)
print out
def main():
app = QtGui.QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
Sorry, I have PyQt5. Try it:
flags Qt::MatchFlags
This enum describes the type of matches that can be used when searching for items in a model.
import sys
#from PyQt4.QtGui import *
#from PyQt4.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
class Example(QWidget):
def __init__(self):
super(Example, self).__init__()
self.initUI()
def initUI(self):
self.le_search = QLineEdit() # self. +++
se_btn = QPushButton("Search")
se_btn.clicked.connect(self.find_item)
self.listwidget = QListWidget()
self.total_list = ["machine", "mac1", "printer", "Printer","xerox bundles", "2mac"]
self.listwidget.addItems(self.total_list)
hbox = QHBoxLayout()
hbox.addWidget(self.le_search) # self. +++
hbox.addWidget(se_btn)
auto_search_vbox = QVBoxLayout(self)
auto_search_vbox.addLayout(hbox)
auto_search_vbox.addWidget(self.listwidget)
def find_item(self):
# out = self.listwidget.findItems("mac", QtCore.Qt.MatchExactly) # ---
# out = self.listwidget.findItems(self.le_search.text(), Qt.MatchExactly)
out = self.listwidget.findItems(self.le_search.text(),
Qt.MatchContains | # +++
Qt.MatchCaseSensitive) # +++
print("out->", [ i.text() for i in out ] )
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Example()
ex.show()
sys.exit(app.exec_())

Trouble with Importing Data and displaying it on a graph on a button click in python

from PyQt4.uic import loadUiType
import pandas as pd
from matplotlib.figure import Figure
from matplotlib.backends.backend_qt4agg import (
FigureCanvasQTAgg as FigureCanvas,
NavigationToolbar2QT as NavigationToolbar)
Ui_MainWindow, QMainWindow = loadUiType('EIA_20151504_v2.ui')
the above code i have done the following. I have imported the UI designed using QI designer and called matplotlib backend for putting matplotlib greaph in my app
class Main(QMainWindow, Ui_MainWindow):
def __init__(self, ):
super(Main, self).__init__()
self.setupUi(self)
self.RawData.clicked.connect(self.importdata)
def addmpl(self, fig):
self.canvas = FigureCanvas(fig)
self.mplvl.addWidget(self.canvas)
self.canvas.draw()
self.toolbar = NavigationToolbar(self.canvas,
self.MapCanvas, coordinates=True)
self.mplvl.addWidget(self.toolbar)
self.canvas.show()
def importdata(self):
choice = QtGui.QMessageBox.question(self, 'Import Data',"Do you want to import data?", QtGui.QMessageBox.Yes |QtGui.QMessageBox.No,QtGui.QMessageBox.No)
if choice == QtGui.QMessageBox.Yes:
xlsfile = pd.ExcelFile('import_file.xlsx')
self.dframe = xlsfile.parse('Sheet1', header=0, index_col=0, has_index_names=True)
self.xList = self.dframe.columns.values
self.xList = pd.to_datetime(self.xList)
self.yList = self.dframe.values
self.yList = self.yList.T
ax1f1.plot(self.xList,self.yList)
else:
pass
In the above code, I have declared a class Main which initialises the UI code imported from Qt designer and there are tw functions one is to initialise the map canvas and other to import data from another file and plot it on the click of the RawData button.
but if you try to run the code, the graph doesnot display any content
if __name__ == '__main__':
import sys
from PyQt4 import QtGui
import numpy as np
fig1 = Figure()
ax1f1 = fig1.add_subplot(111)
app = QtGui.QApplication(sys.argv)
main = Main()
main.addmpl(fig1)
main.show()
sys.exit(app.exec_())
Kindly let me know where I am going wrong
class Main(QMainWindow, Ui_MainWindow):
def __init__(self, ):
super(Main, self).__init__()
self.setupUi(self)
self.RawData.clicked.connect(self.importdata)
def addmpl(self, fig):
self.canvas = FigureCanvas(fig)
self.mplvl.addWidget(self.canvas)
self.canvas.draw()
self.toolbar = NavigationToolbar(self.canvas,
self.MapCanvas, coordinates=True)
self.mplvl.addWidget(self.toolbar)
self.canvas.show()
def rmmpl(self,):
self.mplvl.removeWidget(self.canvas)
self.canvas.close()
self.mplvl.removeWidget(self.toolbar)
self.toolbar.close()
def importdata(self):
choice = QtGui.QMessageBox.question(self, 'Import Data',"Do you want to import data?", QtGui.QMessageBox.Yes |QtGui.QMessageBox.No,QtGui.QMessageBox.No)
if choice == QtGui.QMessageBox.Yes:
xlsfile = pd.ExcelFile('import_file.xlsx')
self.dframe = xlsfile.parse('Sheet1', header=0, index_col=0, has_index_names=True)
self.xList = self.dframe.columns.values
self.xList = pd.to_datetime(self.xList)
self.yList = self.dframe.values
self.yList = self.yList.T
ax1f1.plot(self.xList,self.yList)
self.rmmpl()
self.addmpl(fig1)
else:
pass
def transition(self):
if __name__ == '__main__':
import sys
from PyQt4 import QtGui
import numpy as np
fig1 = Figure()
ax1f1 = fig1.add_subplot(111)
app = QtGui.QApplication(sys.argv)
main = Main()
main.addmpl(fig1)
main.show()
sys.exit(app.exec_())
There were some minor mistakes which I rectified.

python Attributes error

i just want to ask, what's wrong with my codes, or am i missing something. because when i call the function PausePlay() in the PlayAndPause() I always get an error saying:
self.dbusIfaceKey.Action(dbus.Int32("16"))
AttributeError: 'OpenOMX' object has no attribute 'dbusIfaceKey'
Here's the code:
OPTIONS = 'omxplayer -o local -t on --align center --win "0 0 {1} {2}" \"{0}\"'
from PyQt4 import QtCore, QtGui
from PyQt4.QtGui import *
from Tkinter import *
import sys
import os
from os import system
import dbus,time
from subprocess import Popen
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
_fromUtf8 = lambda s: s
MoviePath = '/media/HP v250w/Our Story in 1 Minute.mp4'
class OpenOMX(QtCore.QThread):
def __init__(self):
QtCore.QThread.__init__(self)
def run(self):
global MoviePath
global myctr
width = QtGui.QApplication.desktop().width()
height = QtGui.QApplication.desktop().height()
cmd = OPTIONS.format(MoviePath,width,height-60)
Popen([cmd], shell=True)
done,retry = 0,0
while done==0:
try:
with open('/tmp/omxplayerdbus', 'r+') as f:
omxplayerdbus = f.read().strip()
bus = dbus.bus.BusConnection(self.omxplayerdbus)
print 'connected'
object = bus.get_object('org.mpris.MediaPlayer2.omxplayer','/org/mpris/MediaPlayer2', introspect=False)
self.dbusIfaceProp = dbus.Interface(object,'org.freedesktop.DBus.Properties')
self.dbusIfaceKey = dbus.Interface(object,'org.mpris.MediaPlayer2.Player')
done=1
except:
retry+=1
if retry >= 50:
print 'ERROR'
raise SystemExit
def PausePlay(self):
self.dbusIfaceKey.Action(dbus.Int32('16'))
class VidControls(QtGui.QMainWindow):
def __init__(self):
QtGui.QMainWindow.__init__(self)
def setupUi(self, MainWindow):
'some codes here'
def retranslateUi(self, MainWindow):
self.btnPause.clicked.connect(self.PlayAndPause)
def PlayAndPause(self):
self.opn = OpenOMX()
self.opn.PausePlay()
if __name__=='__main__':
app = QtGui.QApplication(sys.argv)
ex = VidControls()
ex.show()
play = OpenOMX()
play.start()
sys.exit(app.exec_())
Any Comments or Suggestions would be highly appreciated. Thanks.