Connecting and sending a message in bluetooth using python and PyQt5 - qt

I have been trying to connect to a Bluetooth device (regular, not low energy - an HC-06) using PyQt5 but with no success. I can connect to the same device using standard python calls. I am running Python 3.7 on MacOS. When I run the below code, I get the error: 'unknown error', I'd be happy to know what I am doing wrong.
import sys
import bluetooth
import os
from PyQt5.QtWidgets import QApplication, QWidget
from PyQt5.QtCore import Qt
from PyQt5 import QtBluetooth
class bluetoothTest(QWidget):
def __init__(self, parent = None):
super(bluetoothTest, self).__init__(parent)
self.connectToRobot()
self.app = QApplication(sys.argv)
self.win = QWidget()
self.win.show()
sys.exit(self.app.exec_())
def connectToRobot(self):
self.sock = QtBluetooth.QBluetoothSocket(bluetooth.RFCOMM)
self.sock.connected.connect(self.connectedToBluetooth)
self.sock.readyRead.connect(self.receivedBluetoothMessage)
self.sock.disconnected.connect(self.disconnectedFromBluetooth)
self.sock.error.connect(self.socketError)
port = 1
self.sock.connectToService(QtBluetooth.QBluetoothAddress("98:D3:C1:FD:2C:46"),port)
def socketError(self,error):
print(self.sock.errorString())
def connectedToBluetooth(self):
self.sock.write('A'.encode())
def disconnectedFromBluetooth(self):
self.print('Disconnected from bluetooth')
def receivedBluetoothMessage(self):
while sock.canReadLine():
line = sock.readLine()
print(line)
def main():
# deal with a bluetooth bug on mac
if sys.platform == 'darwin':
os.environ['QT_EVENT_DISPATCHER_CORE_FOUNDATION'] = '1'
app = QApplication(sys.argv)
ex = bluetoothTest()
ex.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()

The problem with my code was the mixing of "regular" Bluetooth and Qt Bluetooth functions, in particular this line:
self.sock = QtBluetooth.QBluetoothSocket(bluetooth.RFCOMM)
which should have been
self.sock = QtBluetooth.QBluetoothSocket(QtBluetooth.QBluetoothServiceInfo.RfcommProtocol)
Here is the complete working code example:
import sys
import os
from PyQt5.QtWidgets import QApplication, QWidget
from PyQt5.QtCore import Qt
from PyQt5 import QtBluetooth
class bluetoothTest(QWidget):
def __init__(self, parent = None):
super(bluetoothTest, self).__init__(parent)
self.connectToRobot()
self.win = QWidget()
self.win.show()
def connectToRobot(self):
self.sock = QtBluetooth.QBluetoothSocket(QtBluetooth.QBluetoothServiceInfo.RfcommProtocol)
self.sock.connected.connect(self.connectedToBluetooth)
self.sock.readyRead.connect(self.receivedBluetoothMessage)
self.sock.disconnected.connect(self.disconnectedFromBluetooth)
self.sock.error.connect(self.socketError)
port = 1
self.sock.connectToService(QtBluetooth.QBluetoothAddress("98:D3:C1:FD:2C:46"),port)
def socketError(self,error):
print(self.sock.errorString())
def connectedToBluetooth(self):
self.sock.write('A'.encode())
def disconnectedFromBluetooth(self):
self.print('Disconnected from bluetooth')
def receivedBluetoothMessage(self):
while self.sock.canReadLine():
line = self.sock.readLine()
print(str(line, "utf-8"))
def main():
# deal with a bluetooth bug on mac
if sys.platform == 'darwin':
os.environ['QT_EVENT_DISPATCHER_CORE_FOUNDATION'] = '1'
app = QApplication(sys.argv)
ex = bluetoothTest()
sys.exit(app.exec_())
if __name__ == '__main__':
main()

Related

QWebEngineView crashes without error output

The page loads, I enter something in the search and the application freezes dead. You can have time to click on some link, but then everything freezes and crashes. There is no error message.
The most interesting thing is that it used to work, and then after some point it stopped (the code did NOT change)
my code:
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5.QtWebEngineWidgets import *
class TabWidget(QTabWidget):
def __init__(self, *args, **kwargs):
QTabWidget.__init__(self, *args, **kwargs)
url = QUrl("https://google.com")
view = HtmlView(self)
view.load(url)
ix = self.addTab(view, "loading ...")
class HtmlView(QWebEngineView):
def __init__(self, *args, **kwargs):
QWebEngineView.__init__(self, *args, **kwargs)
self.tab = self.parent()
def createWindow(self, windowType):
if windowType == QWebEnginePage.WebBrowserTab:
webView = HtmlView(self.tab)
ix = self.tab.addTab(webView, "loading ...")
self.tab.setCurrentIndex(ix)
return webView
return QWebEngineView.createWindow(self, windowType)
if __name__ == "__main__":
import sys
app = QApplication(sys.argv)
main = TabWidget()
main.show()
sys.exit(app.exec_())
I checked the drivers, reinstalled PyQt, but it doesn't help

X button does not fire the closeEvent

I'm trying to use the closeEvent function when the user press X on main window but Python never fired closeEvent function.
I read many posts about this issue but eventually I was not succeeded to resolve this.
Any ideas why?
Here is the code:
import sys
from PyQt5 import QtCore, QtGui, QtWidgets, uic
from PyQt5.QtWidgets import QAction, QMessageBox, QMenu, QWidget
class Ui_MainWindow(object):
def __init__(self):
super(Ui_MainWindow, self).__init__()
print("Initialization succeeded")
def closeEvent(self, event):
print("closeEvent has been called")
userResult = QMessageBox.question(None, "Quit", "Do you want to close the program?", QMessageBox.Yes,
QMessageBox.No)
if userResult == QMessageBox.Yes:
event.accept()
else:
event.ignore()
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(1920, 1080)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("Milvus UI", "Milvus UI"))
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())

Why Draw line in QGraphicScene not show but add button worked in pyqt

when i add pushbutton dynamically to the QGraphicScene with a pic its work but when i use QPainter to draw a line or rectangle not show.
code:
import sys
from PyQt5 import QtWidgets, QtCore, QtGui
from PyQt5.QtGui import QIcon,QPixmap,QPainter,QPainterPath,QBrush,QColor,QPen
class Scene(QtWidgets.QGraphicsScene):
def __init__(self, *args, **kwargs):
super(Scene, self).__init__(*args, **kwargs)
self.path_item = self.addPath(QtGui.QPainterPath())
self.start_point = QtCore.QPointF()
self.end_point = QtCore.QPointF()
def mousePressEvent(self, event):
self.start_point = event.scenePos()
self.end_point = self.start_point
self.update_path()
super().mousePressEvent(event)
def mouseMoveEvent(self, event):
if event.buttons() & QtCore.Qt.LeftButton:
self.end_point = event.scenePos()
self.update_path()
super(Scene, self).mouseMoveEvent(event)
def mouseReleaseEvent(self, event):
self.end_point = event.scenePos()
self.update_path()
super(Scene, self).mouseReleaseEvent(event)
def update_path(self):
if not self.start_point.isNull() and not self.end_point.isNull():
path = QtGui.QPainterPath()
path.moveTo(self.start_point)
path.lineTo(self.end_point)
self.path_item.setPath(path)
def main():
app = QtWidgets.QApplication(sys.argv)
view = QtWidgets.QGraphicsView()
view.setRenderHint(QtGui.QPainter.Antialiasing)
view.setMouseTracking(True)
pix = QPixmap('assets/data.png')
mainpic = QtWidgets.QGraphicsPixmapItem(pix)
scene = Scene()
scene.addItem(mainpic)
view.setScene(scene)
view.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
I think my problem in mouse event but if i disable pic in GraphicsScene draw line correctly worked.

PYQT4 Python 3.4 Creating a form with lable

I am trying to create a window with a label and i get this error
File "ui.py", line 16, in mainWindow = MyForm() File
"ui.py", line 9, in init lbl = QtGui.QLable('Welcome Brats!',
self) ttributeError: 'module' object has no attribute 'QLable'
import sys
from PyQt4 import QtGui
class MyForm(QtGui.QWidget):
def __init__(self):
super(MyForm, self).__init__()
lbl = QtGui.QLable('Welcome Brats!', self)
self.setGeometry(300,300,250,150)
self.setWindowTitle(('Port Scaner'))
self.show()
app = QtGui.QApplication(sys.argv)
mainWindow = MyForm()
status = app.exec_()
sys.exit(status)
Pyqt4 python3.4

Capture mouse position outside QMainWindow (without click)

I tried:
self.installEventFilter(self)
and:
desktop= QApplication.desktop()
desktop.installEventFilter(self)
With:
def eventFilter(self, source, event):
if event.type() == QEvent.MouseMove:
print(event.pos())
return QMainWindow.eventFilter(self, source, event)
In QMainWindow object but nothing conclusive.
Do you have any idea?
Mouse events are initially handled by the window-manager, which then passes them on to whatever window is in that region of the screen. So if there are no Qt windows in that region, you won't get any events (including mouse events).
However, it is still possible to track the cursor position via polling:
from PyQt4 import QtCore, QtGui
class Window(QtGui.QWidget):
cursorMove = QtCore.pyqtSignal(object)
def __init__(self):
super(Window, self).__init__()
self.cursorMove.connect(self.handleCursorMove)
self.timer = QtCore.QTimer(self)
self.timer.setInterval(50)
self.timer.timeout.connect(self.pollCursor)
self.timer.start()
self.cursor = None
def pollCursor(self):
pos = QtGui.QCursor.pos()
if pos != self.cursor:
self.cursor = pos
self.cursorMove.emit(pos)
def handleCursorMove(self, pos):
print(pos)
if __name__ == '__main__':
import sys
app = QtGui.QApplication(sys.argv)
window = Window()
window.setGeometry(500, 500, 200, 200)
window.show()
sys.exit(app.exec_())

Resources