Search Results

Search found 26 results on 2 pages for 'qthread'.

Page 1/2 | 1 2  | Next Page >

  • Qthread - trouble shutting down threads

    - by Bryan Greenway
    For the last few days, I've been trying out the new preferred approach for using QThreads without subclassing QThread. The trouble I'm having is when I try to shutdown a set of threads that I created. I regularly get a "Destroyed while thread is still running" message (if I'm running in Debug mode, I also get a Segmentation Fault dialog). My code is very simple, and I've tried to follow the examples that I've been able to find on the internet. My basic setup is as follows: I've a simple class that I want to run in a separate thread; in fact, I want to run 5 instances of this class, each in a separate thread. I have a simple dialog with a button to start each thread, and a button to stop each thread (10 buttons). When I click one of the "start" buttons, a new instance of the test class is created, a new QThread is created, a movetothread is called to get the test class object to the thread...also, since I have a couple of other members in the test class that need to move to the thread, I call movetothread a few additional times with these other items. Note that one of these items is a QUdpSocket, and although this may not make sense, I wanted to make sure that sockets could be moved to a separate thread in this fashion...I haven't tested the use of the socket in the thread at this point. Starting of the threads all seem to work fine. When I use the linux top command to see if the threads are created and running, they show up as expected. The problem occurs when I begin stopping the threads. I randomly (or it appears to be random) get the error described above. Class that is to run in separate thread: // Declaration class TestClass : public QObject { Q_OBJECT public: explicit TestClass(QObject *parent = 0); QTimer m_workTimer; QUdpSocket m_socket; Q_SIGNALS: void finished(); public Q_SLOTS: void start(); void stop(); void doWork(); }; // Implementation TestClass::TestClass(QObject *parent) : QObject(parent) { } void TestClass::start() { connect(&m_workTimer, SIGNAL(timeout()),this,SLOT(doWork())); m_workTimer.start(50); } void TestClass::stop() { m_workTimer.stop(); emit finished(); } void TestClass::doWork() { int j; for(int i = 0; i<10000; i++) { j = i; } } Inside my main app, code called to start the first thread (similar code exists for each of the other threads): mp_thread1 = new QThread(); mp_testClass1 = new TestClass(); mp_testClass1->moveToThread(mp_thread1); mp_testClass1->m_socket.moveToThread(mp_thread1); mp_testClass1->m_workTimer.moveToThread(mp_thread1); connect(mp_thread1, SIGNAL(started()), mp_testClass1, SLOT(start())); connect(mp_testClass1, SIGNAL(finished()), mp_thread1, SLOT(quit())); connect(mp_testClass1, SIGNAL(finished()), mp_testClass1, SLOT(deleteLater())); connect(mp_testClass1, SIGNAL(finished()), mp_thread1, SLOT(deleteLater())); connect(this,SIGNAL(stop1()),mp_testClass1,SLOT(stop())); mp_thread1->start(); Also inside my main app, this code is called when a stop button is clicked for a specific thread (in this case thread 1): emit stop1(); Sometimes it appears that threads are stopped and destroyed without issue. Other times, I get the error described above. Any guidance would be greatly appreciated. Thanks, Bryan

    Read the article

  • Télécharger un fichier du Web avec PyQt4 et QThread, un article de Jean-Paul Vidal

    Bonjour, Je vous informe d'un nouveau tuto sur developpez : comment télécharger un fichier sur le Web avec PyQt4. Le code utilise QThread (le thread de Qt4) et, pour le téléchargement, le module urllib. Il permet de montrer comment les threads peuvent communiquer par messages avec l'interface graphique afin de mettre à jour une barre de progression du téléchargement. Il a été développé suite au fil de discussion http://www.developpez.net/forums/d10...s-urlretrieve/. Tyrtamos...

    Read the article

  • PyQt4, QThread and opening big files without freezing the GUI

    - by jmrbcu
    Hi, I would like to ask how to read a big file from disk and maintain the PyQt4 UI responsive (not blocked). I had moved the load of the file to a QThread subclass but my GUI thread get freezed. Any suggestions? I think it must be something with the GIL but I don't know how to sort it? EDIT: I am using vtkGDCMImageReader from the GDCM project to read a multiframe DICOM image and display it with vtk and pyqt4. I do this load in a different thread (QThread) but my app freeze until the image is loaded. here is an example code: class ReadThread(QThread): def __init__(self, file_name): super(ReadThread, self).__init__(self) self.file_name = file_name self.reader.vtkgdcm.vtkGDCMImageReader() def run(self): self.reader.SetFileName(self.file_name) self.reader.Update() self.emit(QtCore.SIGNAL('image_loaded'), self.reader.GetOutput())

    Read the article

  • Is it safe to draw three separate QImages in three separate QThreads?

    - by yan bellavance
    I have a QMainWindow with three widgets inside that are promoted to a class containing a subclassed QThread. They each draw on a local QImage in their rexpective qthread which is sent with a signal once its drawn and then rendered by calling update (mandlebrot example) from the slot. Is this safe or dangerous? They do not share any data, at least none that I am generating and am wondering what data they could be sharing that is outside of my coding range ie that is generated by Qt automatically.

    Read the article

  • qapps runs well but breakpoint sometimes generates segmentation fault

    - by yan bellavance
    I have a qApp that generates a segmentation fault only when a breakpoint is inserted in the code (I can put it at different places) and only after 4-5 breakpoint stops. Do I have a problem with my code or is this a DBG bug. the method is part of a QThread Class. Basically what I did is i took the mandlebrot example, and have 3 instances of it in my program. So the program would look like a mainwindow that has 3 mandlebrot widgets in it, one besides the other. Is it possible that GDB doesnt support debugging qthread subclasses that are instantiated multiple times or is it thread-unsafe to do so. I dont have any problems at run-time.

    Read the article

  • How to update QStandartItemModel without freezing the main UI

    - by user1044002
    I'm starting to learn PyQt4 and have been stuck on something for a long time now and can't figure it out myself: Here is the concept: There is a TreeView with custom QStandartItemModel, which gets rebuild every couple of seconds, and can have a lot (hundreds at least) of entries, there also will be additional delegates for the different columns etc. It's fairly complex and the building time for even plain model, without delegates, goes up to .3 sec, which makes the TreeView to freeze. Please advice me for the best approach on solving this. I was thing of somehow building the model in different thread, and eventually sending it to the TreeView, where it would just perform setModel() with the new one, but couldn't make that work. here is some code that may illustrate the problem a bit: from PyQt4.QtCore import * from PyQt4.QtGui import * import sys, os, re, time app = QApplication(sys.argv) REFRESH = 1 class Reloader_Thread(QThread): def __init__(self, parent = None): QThread.__init__(self, parent) self.loaders = ['\\', '--', '|', '/', '--'] self.emit(SIGNAL('refresh')) def run(self): format = '|%d/%b/%Y %H:%M:%S| ' while True: self.emit(SIGNAL('refresh')) self.sleep(REFRESH) class Model(QStandardItemModel): def __init__(self, viewer=None): QStandardItemModel.__init__(self,None) self.build() def build(self): stTime = time.clock() newRows = [] for r in range(1000): row = [] for c in range(12): item = QStandardItem('%s %02d%02d' % (time.strftime('%H"%M\'%S'), r,c)) row.append(item) newRows.append(row) eTime = time.clock() - stTime outStr = 'Build %03f' % eTime format = '|%d/%b/%Y %H:%M:%S| ' stTime = time.clock() self.beginRemoveRows(QModelIndex(), 0, self.rowCount()) self.removeRows(0, self.rowCount()) self.endRemoveRows() eTime = time.clock() - stTime outStr += ', Remove %03f' % eTime stTime = time.clock() numNew = len(newRows) for r in range(numNew): self.appendRow(newRows[r]) eTime = time.clock() - stTime outStr += ', Set %03f' % eTime self.emit(SIGNAL('status'), outStr) self.reset() w = QWidget() w.setGeometry(200,200,800,600) hb = QVBoxLayout(w) tv = QTreeView() tvm = Model(tv) tv.setModel(tvm) sb = QStatusBar() reloader = Reloader_Thread() tvm.connect(tvm, SIGNAL('status'), sb.showMessage) reloader.connect(reloader, SIGNAL('refresh'), tvm.build) reloader.start() hb.addWidget(tv) hb.addWidget(sb) w.show() app.setStyle('plastique') app.processEvents(QEventLoop.AllEvents) app.aboutToQuit.connect(reloader.quit) app.exec_()

    Read the article

  • pyqt QObject: Cannot create children for a parent that is in a different thread

    - by memomk
    QObject: Cannot create children for a parent that is in a different thread. (Parent is QTextDocument(0x9919018), parent's thread is QThread(0x97331e0), current thread is flooderthread(0x97b4c10) error means ? am sorry because am new to pyqt here is the code : i know the code is finished yet but it should work i guess the problem is with myfun.log function... #! /usr/bin/python # -*- coding: utf-8 -*- import urllib, urllib2, itertools, threading, cookielib, Cookie, sys, time, hashlib, os from PyQt4 import QtCore, QtGui try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: _fromUtf8 = lambda s: s gui=QtGui.QApplication.processEvents texttoset="" class fun(): global texttoset def checkpassword(self): if ui.passwordcheck.isChecked()==True: return 1 else : return 0 def log(self, text): if text != False: firsttext=str(ui.console.toPlainText()) secondtext=firsttext+text+"\n" ui.console.setText(secondtext) log=open("log.log", "a") log.write(text+"\n") log.close() else : firsttext=str(ui.console.toPlainText()) secondtext=firsttext+texttoset+"\n" ui.console.setText(secondtext) log=open("log.log", "a") log.write(texttoset+"\n") log.close() def disable(self): MainWindow.setEnabled(False) pass def enable(self): MainWindow.setEnabled(True) pass def checkmethod(self): if ui.get.isChecked()==True: return 1 elif ui.post.isChecked()==True: return 2 else : return 0 def main(self): connecter() gui() f1.start() gui() time.sleep(3) gui() f2.start() gui() time.sleep(3) gui() f3.start() gui() time.sleep(3) gui() f4.start() gui() time.sleep(3) gui() f5.start() gui() self.sleep(3) gui() f6.start() gui() def killer(self): f1.terminate() f2.terminate() f3.terminate() f4.terminate() f5.terminate() f6.terminate() def close(self): self.killer() os.abort() sys.exit() myfun=fun() def connecter(): QtCore.QObject.connect(f1, QtCore.SIGNAL("log(bool)"), myfun.log) QtCore.QObject.connect(f1, QtCore.SIGNAL("enable()"), myfun.enable) QtCore.QObject.connect(f1, QtCore.SIGNAL("disable()"), myfun.disable) QtCore.QObject.connect(f2, QtCore.SIGNAL("log(bool)"), myfun.log) QtCore.QObject.connect(f2, QtCore.SIGNAL("enable()"), myfun.enable) QtCore.QObject.connect(f2, QtCore.SIGNAL("disable()"), myfun.disable) QtCore.QObject.connect(f3, QtCore.SIGNAL("log(bool)"), myfun.log) QtCore.QObject.connect(f3, QtCore.SIGNAL("enable()"), myfun.enable) QtCore.QObject.connect(f3, QtCore.SIGNAL("disable()"), myfun.disable) QtCore.QObject.connect(f4, QtCore.SIGNAL("log(bool)"), myfun.log) QtCore.QObject.connect(f4, QtCore.SIGNAL("enable()"), myfun.enable) QtCore.QObject.connect(f4, QtCore.SIGNAL("disable()"), myfun.disable) QtCore.QObject.connect(f5, QtCore.SIGNAL("log(bool)"), myfun.log) QtCore.QObject.connect(f5, QtCore.SIGNAL("enable()"), myfun.enable) QtCore.QObject.connect(f5, QtCore.SIGNAL("disable()"), myfun.disable) QtCore.QObject.connect(f6, QtCore.SIGNAL("log(bool)"), myfun.log) QtCore.QObject.connect(f6, QtCore.SIGNAL("enable()"), myfun.enable) QtCore.QObject.connect(f6, QtCore.SIGNAL("disable()"), myfun.disable) x=0 num=0 class flooderthread(QtCore.QThread): global texttoset def __init__(self, x, num): QtCore.QThread.__init__(self) self.x=x self.num=num def log(self, text): texttolog=str(text) time.sleep(1) self.emit(QtCore.SIGNAL("log(bool)"), False) time.sleep(2) def enable(self): time.sleep(1) self.emit(QtCore.SIGNAL("enable()")) def disable(self): time.sleep(1) self.emit(QtCore.SIGNAL("disable()")) def run(self): connecter() self.log("\n\n--------------------------------------------------new session-------------------------------------\n\n") itered=False gui() self.disable() gui() self.log("setting params...") param={ui.dataname1.text():ui.datavalue1.text(),ui.dataname3.text():ui.datavalue3.text(),ui.dataname3.text():ui.datavalue3.text(), } self.log("checking password...") if myfun.checkpassword()==1: itered=True self.log("password is true") else : self.log("password is null ") self.log("itered operation") self.log("setting url") url=str(ui.url.text()) if url[:4]!="http" and url[:3]!="ftp": self.log("url error exiting the whole function") self.log("please set a valide protocole!!") gui() self.enable() gui() return 1 pass else : self.log("valid url") gui() self.log("url is "+url) self.log("setting proxy") proxy="http://"+ui.proxyuser.text()+":"+ui.proxypass.text()+"@"+ui.proxyhost.text()+":"+ui.proxyport.text() self.log("proxy is "+proxy) gui() self.log("preparing params...") urlparam=urllib.urlencode(param) gui() self.log("params are "+urlparam) self.log("setting up headers...") header={'User-Agent':str(ui.useragent.toPlainText())} self.log("headers are "+ str(header)) self.log("setting up proxy handler..") proxyhandler=urllib2.ProxyHandler({"http":str(proxy)}) self.log("checking method") if myfun.checkmethod()==1: self.log("method is get..") self.log("setting request..") finalurl=url+urlparam gui() self.log("final url is"+finalurl) req=urllib2.Request(finalurl, None, headers) elif myfun.checkmethod()==2: self.log("method is post...") self.log("setting request..") finalurl=url gui() self.log("final url is "+finalurl) req=urllib2.Request(finalurl, urlparam, header) else : self.log("error has been accourded") self.log("please select a method!!") gui() self.log("exiting the whole functions") gui() self.enable() return 1 pass self.log("intilizing cookies..") c1=Cookie.SimpleCookie() c1[str(ui.cookiename1.text())]=str(ui.cookievalue1.text()) c1[str(ui.cookiename1.text())]['path']='/' c1[str(ui.cookiename2.text())]=str(ui.cookievalue2.text()) c1[str(ui.cookiename2.text())]['path']='/' c1[str(ui.cookiename3.text())]=str(ui.cookievalue3.text()) c1[str(ui.cookiename3.text())]['domain']=url c1[str(ui.cookiename3.text())]['path']='/' c1[str(ui.cookiename4.text())]=str(ui.cookievalue4.text()) c1[str(ui.cookiename4.text())]['domain']=url c1[str(ui.cookiename4.text())]['path']='/' self.log("cookies are.. :"+str(c1)) cj=cookielib.CookieJar() cj.set_cookie(c1) opener = urllib2.build_opener(proxyhandler, urllib2.HTTPCookieProcessor(cj)) self.log("insatlling opener") urllib2.install_opener(opener) self.log("setting the two operations....") if itered==Fasle: self.log("starting the flooding loop") gui() while true: try: gui() opener.open(req) except e: self.log("error connecting : "+e.reason) self.log("will continue....") continue gui() elif itered==True: pass f1=flooderthread(1, 1) f2=flooderthread(2, 2) f3=flooderthread(3, 3) f4=flooderthread(4, 4) f5=flooderthread(5, 5) f6=flooderthread(6, 6) class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.setObjectName(_fromUtf8("MainWindow")) MainWindow.setMinimumSize(QtCore.QSize(838, 500)) MainWindow.setMaximumSize(QtCore.QSize(838, 500)) MainWindow.setWindowTitle(QtGui.QApplication.translate("MainWindow", "memo flooder", None, QtGui.QApplication.UnicodeUTF8)) self.centralwidget = QtGui.QWidget(MainWindow) self.centralwidget.setObjectName(_fromUtf8("centralwidget")) self.console=QtGui.QTextEdit(self.centralwidget) self.console.setGeometry(10, 350, 800,130) self.console.setReadOnly(True) self.console.setObjectName("console") self.groupBox = QtGui.QGroupBox(self.centralwidget) self.groupBox.setGeometry(QtCore.QRect(30, 50, 71, 80)) self.groupBox.setTitle(QtGui.QApplication.translate("MainWindow", "method:", None, QtGui.QApplication.UnicodeUTF8)) self.groupBox.setObjectName(_fromUtf8("groupBox")) self.post = QtGui.QRadioButton(self.groupBox) self.post.setGeometry(QtCore.QRect(10, 20, 61, 22)) self.post.setText(QtGui.QApplication.translate("MainWindow", "post", None, QtGui.QApplication.UnicodeUTF8)) self.post.setChecked(True) self.post.setObjectName(_fromUtf8("post")) self.get = QtGui.QRadioButton(self.groupBox) self.get.setGeometry(QtCore.QRect(10, 50, 51, 22)) self.get.setText(QtGui.QApplication.translate("MainWindow", "get", None, QtGui.QApplication.UnicodeUTF8)) self.get.setObjectName(_fromUtf8("get")) self.url = QtGui.QLineEdit(self.centralwidget) self.url.setGeometry(QtCore.QRect(70, 20, 671, 27)) self.url.setInputMethodHints(QtCore.Qt.ImhUrlCharactersOnly) self.url.setObjectName(_fromUtf8("url")) self.groupBox_2 = QtGui.QGroupBox(self.centralwidget) self.groupBox_2.setGeometry(QtCore.QRect(110, 50, 371, 111)) self.groupBox_2.setTitle(QtGui.QApplication.translate("MainWindow", "data:", None, QtGui.QApplication.UnicodeUTF8)) self.groupBox_2.setObjectName(_fromUtf8("groupBox_2")) self.dataname1 = QtGui.QLineEdit(self.groupBox_2) self.dataname1.setGeometry(QtCore.QRect(20, 30, 101, 27)) self.dataname1.setObjectName(_fromUtf8("dataname1")) self.label = QtGui.QLabel(self.groupBox_2) self.label.setGeometry(QtCore.QRect(40, 10, 67, 17)) self.label.setText(QtGui.QApplication.translate("MainWindow", "name:", None, QtGui.QApplication.UnicodeUTF8)) self.label.setObjectName(_fromUtf8("label")) self.dataname2 = QtGui.QLineEdit(self.groupBox_2) self.dataname2.setGeometry(QtCore.QRect(130, 30, 113, 27)) self.dataname2.setObjectName(_fromUtf8("dataname2")) self.dataname3 = QtGui.QLineEdit(self.groupBox_2) self.dataname3.setGeometry(QtCore.QRect(250, 30, 113, 27)) self.dataname3.setObjectName(_fromUtf8("dataname3")) self.label_2 = QtGui.QLabel(self.groupBox_2) self.label_2.setGeometry(QtCore.QRect(40, 60, 67, 17)) self.label_2.setText(QtGui.QApplication.translate("MainWindow", "value:", None, QtGui.QApplication.UnicodeUTF8)) self.label_2.setObjectName(_fromUtf8("label_2")) self.datavalue1 = QtGui.QLineEdit(self.groupBox_2) self.datavalue1.setGeometry(QtCore.QRect(20, 80, 101, 27)) self.datavalue1.setObjectName(_fromUtf8("datavalue1")) self.datavalue2 = QtGui.QLineEdit(self.groupBox_2) self.datavalue2.setGeometry(QtCore.QRect(130, 80, 113, 27)) self.datavalue2.setObjectName(_fromUtf8("datavalue2")) self.datavalue3 = QtGui.QLineEdit(self.groupBox_2) self.datavalue3.setGeometry(QtCore.QRect(250, 80, 113, 27)) self.datavalue3.setObjectName(_fromUtf8("datavalue3")) self.groupBox_4 = QtGui.QGroupBox(self.centralwidget) self.groupBox_4.setGeometry(QtCore.QRect(670, 50, 151, 111)) self.groupBox_4.setTitle(QtGui.QApplication.translate("MainWindow", "password:", None, QtGui.QApplication.UnicodeUTF8)) self.groupBox_4.setObjectName(_fromUtf8("groupBox_4")) self.passname = QtGui.QLineEdit(self.groupBox_4) self.passname.setGeometry(QtCore.QRect(10, 30, 113, 27)) self.passname.setObjectName(_fromUtf8("passname")) self.passvalue = QtGui.QLineEdit(self.groupBox_4) self.passvalue.setGeometry(QtCore.QRect(10, 80, 113, 27)) self.passvalue.setObjectName(_fromUtf8("passvalue")) self.passwordcheck = QtGui.QCheckBox(self.centralwidget) self.passwordcheck.setGeometry(QtCore.QRect(670, 180, 97, 22)) self.passwordcheck.setText(QtGui.QApplication.translate("MainWindow", "password", None, QtGui.QApplication.UnicodeUTF8)) self.passwordcheck.setChecked(True) self.passwordcheck.setObjectName(_fromUtf8("passwordcheck")) self.groupBox_5 = QtGui.QGroupBox(self.centralwidget) self.groupBox_5.setGeometry(QtCore.QRect(29, 169, 441, 81)) self.groupBox_5.setTitle(QtGui.QApplication.translate("MainWindow", "proxy:", None, QtGui.QApplication.UnicodeUTF8)) self.groupBox_5.setObjectName(_fromUtf8("groupBox_5")) self.proxyhost = QtGui.QLineEdit(self.groupBox_5) self.proxyhost.setGeometry(QtCore.QRect(20, 30, 113, 27)) self.proxyhost.setObjectName(_fromUtf8("proxyhost")) self.proxyport = QtGui.QLineEdit(self.groupBox_5) self.proxyport.setGeometry(QtCore.QRect(140, 30, 51, 27)) self.proxyport.setInputMethodHints(QtCore.Qt.ImhDigitsOnly|QtCore.Qt.ImhPreferNumbers) self.proxyport.setObjectName(_fromUtf8("proxyport")) self.proxyuser = QtGui.QLineEdit(self.groupBox_5) self.proxyuser.setGeometry(QtCore.QRect(200, 30, 113, 27)) self.proxyuser.setObjectName(_fromUtf8("proxyuser")) self.proxypass = QtGui.QLineEdit(self.groupBox_5) self.proxypass.setGeometry(QtCore.QRect(320, 30, 113, 27)) self.proxypass.setObjectName(_fromUtf8("proxypass")) self.label_4 = QtGui.QLabel(self.groupBox_5) self.label_4.setGeometry(QtCore.QRect(100, 10, 67, 17)) self.label_4.setText(QtGui.QApplication.translate("MainWindow", "host", None, QtGui.QApplication.UnicodeUTF8)) self.label_4.setObjectName(_fromUtf8("label_4")) self.label_5 = QtGui.QLabel(self.groupBox_5) self.label_5.setGeometry(QtCore.QRect(150, 10, 67, 17)) self.label_5.setText(QtGui.QApplication.translate("MainWindow", "port", None, QtGui.QApplication.UnicodeUTF8)) self.label_5.setObjectName(_fromUtf8("label_5")) self.label_6 = QtGui.QLabel(self.groupBox_5) self.label_6.setGeometry(QtCore.QRect(200, 10, 67, 17)) self.label_6.setText(QtGui.QApplication.translate("MainWindow", "username", None, QtGui.QApplication.UnicodeUTF8)) self.label_6.setObjectName(_fromUtf8("label_6")) self.label_7 = QtGui.QLabel(self.groupBox_5) self.label_7.setGeometry(QtCore.QRect(320, 10, 67, 17)) self.label_7.setText(QtGui.QApplication.translate("MainWindow", "password", None, QtGui.QApplication.UnicodeUTF8)) self.label_7.setObjectName(_fromUtf8("label_7")) self.groupBox_6 = QtGui.QGroupBox(self.centralwidget) self.groupBox_6.setGeometry(QtCore.QRect(30, 260, 531, 91)) self.groupBox_6.setTitle(QtGui.QApplication.translate("MainWindow", "cookies:", None, QtGui.QApplication.UnicodeUTF8)) self.groupBox_6.setObjectName(_fromUtf8("groupBox_6")) self.cookiename1 = QtGui.QLineEdit(self.groupBox_6) self.cookiename1.setGeometry(QtCore.QRect(10, 20, 113, 27)) self.cookiename1.setObjectName(_fromUtf8("cookiename1")) self.cookiename2 = QtGui.QLineEdit(self.groupBox_6) self.cookiename2.setGeometry(QtCore.QRect(140, 20, 113, 27)) self.cookiename2.setObjectName(_fromUtf8("cookename2")) self.cookiename3 = QtGui.QLineEdit(self.groupBox_6) self.cookiename3.setGeometry(QtCore.QRect(270, 20, 113, 27)) self.cookiename3.setObjectName(_fromUtf8("cookiename3")) self.cookiename4 = QtGui.QLineEdit(self.groupBox_6) self.cookiename4.setGeometry(QtCore.QRect(390, 20, 113, 27)) self.cookiename4.setObjectName(_fromUtf8("cookiename4")) self.cookievalue1 = QtGui.QLineEdit(self.groupBox_6) self.cookievalue1.setGeometry(QtCore.QRect(10, 50, 113, 27)) self.cookievalue1.setObjectName(_fromUtf8("cookievalue1")) self.cookievalue2 = QtGui.QLineEdit(self.groupBox_6) self.cookievalue2.setGeometry(QtCore.QRect(140, 50, 113, 27)) self.cookievalue2.setObjectName(_fromUtf8("cookievalue2")) self.cookievalue3 = QtGui.QLineEdit(self.groupBox_6) self.cookievalue3.setGeometry(QtCore.QRect(270, 50, 113, 27)) self.cookievalue3.setObjectName(_fromUtf8("cookievalue3")) self.cookievalue4 = QtGui.QLineEdit(self.groupBox_6) self.cookievalue4.setGeometry(QtCore.QRect(390, 50, 113, 27)) self.cookievalue4.setObjectName(_fromUtf8("cookievalue4")) self.groupBox_7 = QtGui.QGroupBox(self.centralwidget) self.groupBox_7.setGeometry(QtCore.QRect(570, 260, 251, 80)) self.groupBox_7.setTitle(QtGui.QApplication.translate("MainWindow", "useragents:", None, QtGui.QApplication.UnicodeUTF8)) self.groupBox_7.setObjectName(_fromUtf8("groupBox_7")) self.useragent = QtGui.QTextEdit(self.groupBox_7) self.useragent.setGeometry(QtCore.QRect(10, 20, 211, 51)) self.useragent.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn) self.useragent.setObjectName(_fromUtf8("useragent")) self.start = QtGui.QPushButton(self.centralwidget) self.start.setGeometry(QtCore.QRect(750, 20, 71, 27)) self.start.setText(QtGui.QApplication.translate("MainWindow", "start", None, QtGui.QApplication.UnicodeUTF8)) self.start.setObjectName(_fromUtf8("start")) self.label_3 = QtGui.QLabel(self.centralwidget) self.label_3.setGeometry(QtCore.QRect(30, 20, 67, 17)) self.label_3.setText(QtGui.QApplication.translate("MainWindow", "url :", None, QtGui.QApplication.UnicodeUTF8)) self.label_3.setObjectName(_fromUtf8("label_3")) MainWindow.setCentralWidget(self.centralwidget) QtCore.QObject.connect(self.start, QtCore.SIGNAL(_fromUtf8("clicked(bool)")), myfun.main) QtCore.QObject.connect(self.passwordcheck, QtCore.SIGNAL(_fromUtf8("clicked(bool)")), self.groupBox_4.setEnabled) QtCore.QMetaObject.connectSlotsByName(MainWindow) def __del__(): myfun.killer() os.abort() sys.exit() app = QtGui.QApplication(sys.argv) MainWindow = QtGui.QMainWindow() ui = Ui_MainWindow() ui.setupUi(MainWindow) myfun.log("\n\n--------------------------------------------------new session-------------------------------------\n\n") MainWindow.show() sys.exit(app.exec_())

    Read the article

  • Sending custom PyQt signals?

    - by Enfors
    I'm practicing PyQt and (Q)threads by making a simple Twitter client. I have two Qthreads. Main/GUI thread. Twitter fetch thread - fetches data from Twitter every X minutes. So, every X minutes my Twitter thread downloads a new set of status updates (a Python list). I want to hand this list over to the Main/GUI thread, so that it can update the window with these statuses. I'm assuming that I should be using the signal / slot system to transfer the "statuses" Python list from the Twitter thread, to the Main/GUI thread. So, my question is twofold: How do I send the statuses from the Twitter thread? How do I receive them in the Main/GUI thread? As far as I can tell, PyQt can by default only send PyQt-objects via signals / slots. I think I'm supposed to somehow register a custom signal which I can then send, but the documentation on this that I've found is very unclear to a newbie like me. I have a PyQt book on order, but it won't arrive in another week, and I don't want to wait until then. :-) I'm using PyQt 4.6-1 on Ubuntu Update: This is an excert from the code that doesn't work. First, I try to "connect" the signal ("newStatuses", a name I just made up) to the function self.update_tweet_list in the Main/GUI thread: QtCore.QObject.connect(self.twit_in, QtCore.SIGNAL("newStatuses (statuses)"), self.update_tweet_list) Then, in the Twitter thread, I do this: self.emit(SIGNAL("newStatuses (statuses)"), statuses) When this line is called, I get the following message: QObject::connect: Cannot queue arguments of type 'statuses' (Make sure 'statuses' is registered using qRegisterMetaType().) I did a search for qRegisterMetaType() but I didn't find anything relating to Python that I could understand.

    Read the article

  • Qt: How to use QTimer to print a message to a QTextBrowser every 10 seconds?

    - by Aaron McKellar
    Hello, I have working at this for hours and cannot figure it out nor can I find any help online that works. Basically the gist of what I am trying to accomplish is to have a Qt GUI with a button and a QTextBrowser. When I push the button I want it to diplay a message and then keep printing this message every 10 seconds. I figured I would use QTimer because it makes sense to have a timer to diplay the message every 10 seconds. When I originally implemented this into my buttonClicked() SLOT it caused the program to freeze. I looked online for a solution and found QApplication::processEvents(). So basically in my function I had something like this: while(1) { QTimer *timer; connect(...) //omitted parameters for this example timer.start(10000); ui->diplay->append("Message"); while(timer.isActive()) { QApplication::processEvents() } } I figured it would break out of the timer.isActive() while loop but it won't it simply stays in there. So I figured this is a threading issue. So I figured out how to use QThreads but I still can't get it to work. Basically when I create a thread with a timer on it and the thread tells the timer to start, the program closes and the console says "The program has unexpectedly finished". There has to be an easy way to do this but my track record with Qt has always been that th

    Read the article

  • one timer per thread using Qt

    - by Pourya
    Hi, I modified Qt's broadcast sender example so that it has ten threads and in each thread it starts a timer, but only timer of the first thread is triggered. How can I have one timer running for each thread?

    Read the article

  • Does QThread::sleep() require the event loop to be running?

    - by suszterpatt
    I have a simple client-server program written in Qt, where processes communicate using MPI. The basic design I'm trying to implement is the following: The first process (the "server") launches a GUI (derived from QMainWindow), which listens for messages from the clients (using repeat fire QTimers and asynchronous MPI receive calls), updates the GUI depending on what messages it receives, and sends a reply to every message. Every other process (the "clients") runs in an infinite loop, and all they are intended to do is send a message to the server process, receive the reply, go to sleep for a while, then wake up and repeat. Every process instantiates a single object derived from QThread, and calls its start() method. The run() method of these classes all look like this: from foo.cpp: void Foo::run() { while (true) { // Send message to the first process // Wait for a reply // Do uninteresting stuff with the reply sleep(3); // also tried QThread::sleep(3) } } In the client's code, there is no call to exec() anywhere, so no event loop should start. The problem is that the clients never wake up from sleeping (if I surround the sleep() call with two writes to a log file, only the first one is executed, control never reaches the second). Is this because I didn't start the event loop? And if so, what is the simplest way to achieve the desired functionality?

    Read the article

  • Qt Socket blocking functions required to run in QThread where created. Any way past this?

    - by Alexander Kondratskiy
    The title is very cryptic, so here goes! I am writing a client that behaves in a very synchronous manner. Due to the design of the protocol and the server, everything has to happen sequentially (send request, wait for reply, service reply etc.), so I am using blocking sockets. Here is where Qt comes in. In my application I have a GUI thread, a command processing thread and a scripting engine thread. I create the QTcpSocket in the command processing thread, as part of my Client class. The Client class has various methods that boil down to writing to the socket, reading back a specific number of bytes, and returning a result. The problem comes when I try to directly call Client methods from the scripting engine thread. The Qt sockets randomly time out and when using a debug build of Qt, I get these warnings: QSocketNotifier: socket notifiers cannot be enabled from another thread QSocketNotifier: socket notifiers cannot be disabled from another thread Anytime I call these methods from the command processing thread (where Client was created), I do not get these problems. To simply phrase the situation: Calling blocking functions of QAbstractSocket, like waitForReadyRead(), from a thread other than the one where the socket was created (dynamically allocated), causes random behaviour and debug asserts/warnings. Anyone else experienced this? Ways around it? Thanks in advance.

    Read the article

  • Symbian qt threading

    - by Umesha MS
    Hi, 1) In symbian c++ thread is not recommended. Instead of that they recommend active object for multi tasking. Presently I am using QT to develop a application in symbian. Since there is no active object in QT I thought of using thread. My question is , can I use thread, is it is recommended. If it is not recommended, how to achieve multitasking. 2) I have created a sample thread class as shown bellow. When I call test function from the constructer of the main window thread will start but UI will be in hung state, infact main window itself will not be displayed. Please help me to solve the problem. class CSampleThread: public QThread { Q_OBJECT public: CSampleThread(QObject *parent = 0) : QThread(parent) {} virtual ~CSampleThread() {} void test(){ QThread::start(LowPriority); } protected: void run() { while(true){} } };

    Read the article

  • Qt C++ signals and slots did not fire

    - by Xegara
    I have programmed Qt a couple of times already and I really like the signals and slots feature. But now, I guess I'm having a problem when a signal is emitted from one thread, the corresponding slot from another thread is not fired. The connection was made in the main program. This is also my first time to use Qt for ROS which uses CMake. The signal fired by the QThread triggered their corresponding slots but the emitted signal of my class UserInput did not trigger the slot in tflistener where it supposed to. I have tried everything I can. Any help? The code is provided below. Main.cpp #include <QCoreApplication> #include <QThread> #include "userinput.h" #include "tfcompleter.h" int main(int argc, char** argv) { QCoreApplication app(argc, argv); QThread *thread1 = new QThread(); QThread *thread2 = new QThread(); UserInput *input1 = new UserInput(); TfCompleter *completer = new TfCompleter(); QObject::connect(input1, SIGNAL(togglePause2()), completer, SLOT(toggle())); QObject::connect(thread1, SIGNAL(started()), completer, SLOT(startCounting())); QObject::connect(thread2, SIGNAL(started()), input1, SLOT(start())); completer->moveToThread(thread1); input1->moveToThread(thread2); thread1->start(); thread2->start(); app.exec(); return 0; } What I want to do is.. There are two seperate threads. One thread is for the user input. When the user enters [space], the thread emits a signal to toggle the boolean member field of the other thread. The other thread 's task is to just continue its process if the user wants it to run, otherwise, the user does not want it to run. I wanted to grant the user to toggle the processing anytime that he wants, that's why I decided to bring them into seperate threads. The following codes are the tflistener and userinput. tfcompleter.h #ifndef TFCOMPLETER_H #define TFCOMPLETER_H #include <QObject> #include <QtCore> class TfCompleter : public QObject { Q_OBJECT private: bool isCount; public Q_SLOTS: void toggle(); void startCounting(); }; #endif tflistener.cpp #include "tfcompleter.h" #include <iostream> void TfCompleter::startCounting() { static uint i = 0; while(true) { if(isCount) std::cout << i++ << std::endl; } } void TfCompleter::toggle() { // isCount = ~isCount; std::cout << "isCount " << std::endl; } UserInput.h #ifndef USERINPUT_H #define USERINPUT_H #include <QObject> #include <QtCore> class UserInput : public QObject { Q_OBJECT public Q_SLOTS: void start(); // Waits for the keypress from the user and emits the corresponding signal. public: Q_SIGNALS: void togglePause2(); }; #endif UserInput.cpp #include "userinput.h" #include <iostream> #include <cstdio> // Implementation of getch #include <termios.h> #include <unistd.h> /* reads from keypress, doesn't echo */ int getch(void) { struct termios oldattr, newattr; int ch; tcgetattr( STDIN_FILENO, &oldattr ); newattr = oldattr; newattr.c_lflag &= ~( ICANON | ECHO ); tcsetattr( STDIN_FILENO, TCSANOW, &newattr ); ch = getchar(); tcsetattr( STDIN_FILENO, TCSANOW, &oldattr ); return ch; } void UserInput::start() { char c = 0; while (true) { c = getch(); if (c == ' ') { Q_EMIT togglePause2(); std::cout << "SPACE" << std::endl; } c = 0; } } Here is the CMakeLists.txt. I just placed it here also since I don't know maybe the CMake has also a factor here. CMakeLists.txt ############################################################################## # CMake ############################################################################## cmake_minimum_required(VERSION 2.4.6) ############################################################################## # Ros Initialisation ############################################################################## include($ENV{ROS_ROOT}/core/rosbuild/rosbuild.cmake) rosbuild_init() set(CMAKE_AUTOMOC ON) #set the default path for built executables to the "bin" directory set(EXECUTABLE_OUTPUT_PATH ${PROJECT_SOURCE_DIR}/bin) #set the default path for built libraries to the "lib" directory set(LIBRARY_OUTPUT_PATH ${PROJECT_SOURCE_DIR}/lib) # Set the build type. Options are: # Coverage : w/ debug symbols, w/o optimization, w/ code-coverage # Debug : w/ debug symbols, w/o optimization # Release : w/o debug symbols, w/ optimization # RelWithDebInfo : w/ debug symbols, w/ optimization # MinSizeRel : w/o debug symbols, w/ optimization, stripped binaries #set(ROS_BUILD_TYPE Debug) ############################################################################## # Qt Environment ############################################################################## # Could use this, but qt-ros would need an updated deb, instead we'll move to catkin # rosbuild_include(qt_build qt-ros) rosbuild_find_ros_package(qt_build) include(${qt_build_PACKAGE_PATH}/qt-ros.cmake) rosbuild_prepare_qt4(QtCore) # Add the appropriate components to the component list here ADD_DEFINITIONS(-DQT_NO_KEYWORDS) ############################################################################## # Sections ############################################################################## #file(GLOB QT_FORMS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} ui/*.ui) #file(GLOB QT_RESOURCES RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} resources/*.qrc) file(GLOB_RECURSE QT_MOC RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} FOLLOW_SYMLINKS include/rgbdslam_client/*.hpp) #QT4_ADD_RESOURCES(QT_RESOURCES_CPP ${QT_RESOURCES}) #QT4_WRAP_UI(QT_FORMS_HPP ${QT_FORMS}) QT4_WRAP_CPP(QT_MOC_HPP ${QT_MOC}) ############################################################################## # Sources ############################################################################## file(GLOB_RECURSE QT_SOURCES RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} FOLLOW_SYMLINKS src/*.cpp) ############################################################################## # Binaries ############################################################################## rosbuild_add_executable(rgbdslam_client ${QT_SOURCES} ${QT_MOC_HPP}) #rosbuild_add_executable(rgbdslam_client ${QT_SOURCES} ${QT_RESOURCES_CPP} ${QT_FORMS_HPP} ${QT_MOC_HPP}) target_link_libraries(rgbdslam_client ${QT_LIBRARIES})

    Read the article

  • How to repaint another Qt class

    - by RR
    Hi all, I'm a new bit in Qt... I have a Qt GUI application (written by me), let's call it QtAPP.exe When QtAPP.exe running, I will use a QThread and QProcess to execute some external file, such as player.exe (written in native C). Here's my question: In QtAPP.exe, there are 2 classes, 1. QMainWindow - Core of QtAPP.exe 2. QThread - A thread class to execute external things For now, if I got a finished() signal in that QThread, how do I to force the QMainWindow to repaint itself ? Hope somebody can show me some tips, maybe sample code :) Any suggestion are welcome~

    Read the article

  • undefined reference to `main' collect2: ld returned 1 exit status

    - by sobingt
    I am working on this QT project and i am making test cases for my project. Here is a small test case #include <QApplication> #include <QPalette> #include <QPixmap> #include <QSplashScreen> #include <qthread.h> #define BOOST_TEST_MAIN #include <boost/test/unit_test.hpp> #include <boost/make_shared.hpp> # include <boost/thread.hpp> #include "MainWindow.h" namespace { const std::string dbname = "Project.db"; struct SongFixture { SongFixture(const std::string &fixturePath) { // Create the Master file Master::creator(); // Create/open file std::pair<int, SQLiteDbPtr> result = open( dbname, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0); if (result.first != SQLITE_OK) { throw SQLiteError(result.first, sqlite3_errmsg(result.second.get())); } SQLiteDbPtr &spDb = result.second; // Execute all the SQL from the fixture file execSQLFromFile(spDb, fixturePath); } }; std::auto_ptr<SongFixture> pf; } class I : public QThread { public: static void sleep(unsigned long secs) { QThread::sleep(secs); } }; void free_test_function() { BOOST_CHECK(true ); } test_suite* init_unit_test_suite(int argc, char *argv[]) { // Create a fixture for the peer: // Manage fixture creation manually instead of using // BOOST_FIXTURE_TEST_CASE because the fixture depends on runtime args. std::ostringstream fixturePathSS; fixturePathSS << PROJECT_DIR << "/test/songs_fixture.sql"; std::string fixturePath = fixturePathSS.str(); pf.reset(new SongFixture(fixturePath)); QApplication app(argc, argv); MainWindow window("artists"); window.show(); framework::master_test_suite().add( BOOST_TEST_CASE( &free_test_function )); return app.exec(); } Well i am getting any error /usr/lib/gcc/x86_64-linux-gnu/4.6.1/../../../x86_64-linux-gnu/crt1.o: In function _start': (.text+0x20): undefined reference tomain' collect2: ld returned 1 exit status pls help me you have a lead..thankz I tired adding #define BOOST_TEST_MAIN then i get ../test/UI/main.cpp: In function ‘boost::unit_test::test_suite* init_unit_test_suite(int, char**)’: ../test/UI/main.cpp:75:31: error: redefinition of ‘boost::unit_test::test_suite* init_unit_test_suite(int, char**)’ /usr/local/include/boost/test/unit_test_suite.hpp:223:1: error: ‘boost::unit_test::test_suite* init_unit_test_suite(int, char**)’ previously defined here Well the program is working in Windows but in Linux the above mention problem is observed

    Read the article

  • Can I have multiple instance of the mandlebrot example in one program?

    - by yan bellavance
    Basically what I did is I took the Mandlebrot example and have 3 instances of it in my program. So the program would look like a mainwindow that has 3 mandlebrot widgets in it, one besides the other. Is it possible that GDB doesnt support debugging multiple intances of a classe that derives from qthread or is it thread-unsafe to do so? I don't have any problems at run-time but when I put breakpoints in a function called by the QThread run() function I get a segmentation fault. I can clearly see that the function doesn't complete before returning to the breakpoint ie I the program stops at the breakpoint, I step into the lines of codes one by one but after a couple of instructions another thread startS using the function(even though they are different instances).

    Read the article

  • PyQt threads and signals - how to properly retrieve values

    - by Cawas
    Using Python 2.5 and PyQt, I couldn't find any question this specific in Python, so sorry if I'm repeating the other Qt referenced questions below, but I couldn't easily understand that C code. I've got two classes, a GUI and a thread, and I'm trying to get return values from the thread. I've used the link in here as base to write my code, which is working just fine. To sum it up and illustrate the question in code here (I don't think this code will run on itself): class MainWindow (QtGui.QWidget): # this is just a reference and not really relevant to the question def __init__ (self, parent = None): QtGui.QWidget.__init__(self, parent) self.thread = Worker() # this does not begin a thread - look at "Worker.run" for mor details self.connect(self.thread, QtCore.SIGNAL('finished()'), self.unfreezeUi) self.connect(self.thread, QtCore.SIGNAL('terminated()'), self.unfreezeUi) self.connect(self.buttonDaemon, QtCore.SIGNAL('clicked()'), self.pressDaemon) # the problem begins below: I'm not using signals, or queue, or whatever, while I believe I should def pressDaemon (self): self.buttonDaemon.setEnabled(False) if self.thread.isDaemonRunning(): self.thread.setDaemonStopSignal(True) self.buttonDaemon.setText('Daemon - converts every %s sec'% args['daemonInterval']) else: self.buttonConvert.setEnabled(False) self.thread.startDaemon() self.buttonDaemon.setText('Stop Daemon') self.buttonDaemon.setEnabled(True) # this whole class is just another reference class Worker (QtCore.QThread): daemonIsRunning = False daemonStopSignal = False daemonCurrentDelay = 0 def isDaemonRunning (self): return self.daemonIsRunning def setDaemonStopSignal (self, bool): self.daemonStopSignal = bool def __init__ (self, parent = None): QtCore.QThread.__init__(self, parent) self.exiting = False self.thread_to_run = None # which def will be running def __del__ (self): self.exiting = True self.thread_to_run = None self.wait() def run (self): if self.thread_to_run != None: self.thread_to_run(mode='continue') def startDaemon (self, mode = 'run'): if mode == 'run': self.thread_to_run = self.startDaemon # I'd love to be able to just pass this as an argument on start() below return self.start() # this will begin the thread # this is where the thread actually begins self.daemonIsRunning = True self.daemonStopSignal = False sleepStep = 0.1 # don't know how to interrupt while sleeping - so the less sleepStep, the faster StopSignal will work # begins the daemon in an "infinite" loop while self.daemonStopSignal == False and not self.exiting: # here, do any kind of daemon service delay = 0 while self.daemonStopSignal == False and not self.exiting and delay < args['daemonInterval']: time.sleep(sleepStep) # delay is actually set by while, but this holds for N second delay += sleepStep # daemon stopped, reseting everything self.daemonIsRunning = False self.emit(QtCore.SIGNAL('terminated')) Tho it's quite big, I hope this is pretty clear. The main point is on def pressDaemon. Specifically all 3 self.thread calls. The last one, self.thread.startDaemon() is just fine, and exactly as the example. I doubt that represents any issue. The problem is being able to set the Daemon Stop Signal and retrieve the value if it's running. I'm not sure that it's possible to set a stop signal on QtCore.QtThread, because I've tried doing the same way and it didn't work. But I'm pretty sure it's not possible to retrieve a return result from the emit. So, there it is. I'm using direct calls to the thread class, and I'm almost positive that's not a good design and will probably fail when running under stress. I read about that queue, but I'm not sure it's the proper solution here, or if I should be using Qt at all, since this is Python. And just maybe there's nothing wrong with the way I'm doing.

    Read the article

  • QProcess, QEventLoop - of any use for parallel-processing

    - by dlib
    I wonder whether I could use QEventLoop (QProcess?) to parallelize multiple calls to same function with Qt. What is precisely the difference with QtConcurrent or QThread? What is a process and an event loop more precisely? I read that QCoreApplication must exec() as early as possible in main() method, so that I wonder why it is different from main Thread. could you point as some efficient reference to processes and thread with Qt? I came through the official doc and those things remain unclear. Thanks and regards.

    Read the article

  • Can't catch newConnection() signal from QTcpServer

    - by Bob
    I am trying to make a simple server thread in QT to accept a connection, however although the server is listening (I can connect with my test app) I can't get the newConnection() signal to be acted on. Any help as to what I'm missing here would be much appreciated! class CServerThread : public QThread { Q_OBJECT protected: void run(); private: QTcpServer* server; public slots: void AcceptConnection(); }; void CServerThread::run() { server = new QTcpServer; QObject::connect(server, SIGNAL(newConnection()), this, SLOT(AcceptConnection())); server-listen(QHostAddress::Any, 1000); // Any port in a storm exec(); // Start event loop } void CServerThread::AcceptConnection() { OutputDebugStringA("\n***** INCOMING CONNECTION"); // This is never called! }

    Read the article

  • Large number of simultaneous long-running operations in Qt

    - by Hostile Fork
    I have some long-running operations that number in the hundreds. At the moment they are each on their own thread. My main goal in using threads is not to speed these operations up. The more important thing in this case is that they appear to run simultaneously. I'm aware of cooperative multitasking and fibers. However, I'm trying to avoid anything that would require touching the code in the operations, e.g. peppering them with things like yieldToScheduler(). I also don't want to prescribe that these routines be stylized to be coded to emit queues of bite-sized task items...I want to treat them as black boxes. For the moment I can live with these downsides: Maximum # of threads tend to be O(1000) Cost per thread is O(1MB) To address the bad cache performance due to context-switches, I did have the idea of a timer which would juggle the priorities such that only idealThreadCount() threads were ever at Normal priority, with all the rest set to Idle. This would let me widen the timeslices, which would mean fewer context switches and still be okay for my purposes. Question #1: Is that a good idea at all? One certain downside is it won't work on Linux (docs say no QThread::setPriority() there). Question #2: Any other ideas or approaches? Is QtConcurrent thinking about this scenario? (Some related reading: how-many-threads-does-it-take-to-make-them-a-bad-choice, many-threads-or-as-few-threads-as-possible, maximum-number-of-threads-per-process-in-linux)

    Read the article

  • Calling QAxWidget method outside of the GUI thread

    - by user304361
    I'm beginning to wonder if this is impossible, but I thought I'd ask in case there's a clever way to get around the problems I'm having. I have a Qt application that uses an ActiveX control. The control is held by a QAxWidget, and the QAxWidget itself is contained within another QWidget (I needed to add additional signals/slots to the widget, and I couldn't just subclass QAxWidget because the class doesn't permit that). When I need to interact with the ActiveX control, I call a method of the QWidget, which in turn calls the dynamicCall method of the QAxWidget in order to invoke the appropriate method of the ActiveX control. All of that is working fine. However, one method of the ActiveX control takes several seconds to return. When I call this method, my entire GUI locks up for a few seconds until the method returns. This is undesirable. I'd like the ActiveX control to go off and do its processing by itself and come back to me when it's done without locking up the Qt GUI. I've tried a few things without success: Creating a new QThread and calling QAxWidget::dynamicCall from the new thread Connecting a signal to the appropriate slot method of the QAxWidget and calling the method using signals/slots instead of using dynamicCall Calling QAxWidget::dynamicCall using QtConcurrent::run Nothing seems to affect the behavior. No matter how or where I use dynamicCall (or trigger the appropriate slot of the QAxWidget), the GUI locks until the ActiveX control completes its operation. Is there any way to detach this ActiveX processing from the Qt GUI thread so that the GUI doesn't lock up while the ActiveX control is running a method? Is there something clever I can do with QAxBase or QAxObject to get my desired results?

    Read the article

  • QPainter declared inside a run function creates artifact.

    - by yan bellavance
    I am rendering a QPixmap inside of a QThread. the code to paint is inside a function. If I declare the painter inside the drawChart function everything seems ok but if I declare the painter inside the run function the image is wrong in the sense that at the edge of a black and white area, the pixels at the interface are overlapped to give a grey. Does anyone know why this is so? Could it be because of the nature of the run function itself? //This is ok void RenderThread::run() { QImage image(resultSize, QImage::Format_RGB32); drawChart(&image); emit renderedImage(image, scaleFactor); } drawChart(&image){ QPainter painter(image); painter.doStuff()(; ... } //This gives a image that seems to have artifacts void RenderThread::run() { QImage image(resultSize, QImage::Format_RGB32); QPainter painter(image); drawChart(painter); emit renderedImage(image, scaleFactor); } drawChart(&painter){ painter.doStuff()(; ... }

    Read the article

1 2  | Next Page >