Friday, April 24, 2009

QCoreApplication 和 QApplication

QCoreApplication 是为了编写 console 下 Qt 程序设计的类,提供 event loop,QApplication 继承了它,提供 GUI 下的的 event loop。我们先看看 QCoreApplication,这个类应该是一个 singleton,在其构造函数中调用的 init() 里面有如下代码

Q_ASSERT_X(!self, "QCoreApplication", "there should be only one application object");
QCoreApplication::self = this;
注意与此对应,event dispatcher 对于一个线程也应该是唯一的,
// use the event dispatcher created by the app programmer (if any)
if (!QCoreApplicationPrivate::eventDispatcher)
  QCoreApplicationPrivate::eventDispatcher = d->threadData->eventDispatcher;
// otherwise we create one
if (!QCoreApplicationPrivate::eventDispatcher)
  d->createEventDispatcher();
Q_ASSERT(QCoreApplicationPrivate::eventDispatcher != 0);

if (!QCoreApplicationPrivate::eventDispatcher->parent())
  QCoreApplicationPrivate::eventDispatcher->moveToThread(d->threadData->thread);

d->threadData->eventDispatcher = QCoreApplicationPrivate::eventDispatcher;
类似的,使用 QApplication 时,我们建立了 event dispatcher,创建了 widget 并 QWidget::show() 了,当我们调用 QApplication::exec() 时,进入消息循环,可是消息如何发给我们的 widget 的呢?我们知道前面的 main.cpp 里面甚至没有 QApplication 和 QWidget 的任何关联。 事实是这样的,我们建立一个 QCoreApplication(包括一个 QApplication)对象时,同时建立的 QEventDispatcher 为本 thread 做好了接受 Events 的准备,QWidget 负责创建一个窗体,创建这个部分需要调用底层的 xlib,这时 QEventDispatcher 在该线程某个 xlib 创建的部分收到 X11 的事件后就会获得 event,QEventDispatcherX11::processEvents() 将某一部分 event (用户输入事件)放到一个队列中,还有一部份交给 QApplication::x11PrcessEvent(),该函数负责找到对应的 QWidget 并按照事件类型通过 QWidget::x11Event() 发送过去,注意该函数默认返回 false,
bool QWidget::x11Event(XEvent *)
{
    return false;
}
这是为了让程序员需要的时候自己处理 X11 的事件,因此可以继承 QWidget 覆盖这个函数。我们看看进入消息队列的那部分,
switch (event.type) {
  case ButtonPress:
  case ButtonRelease:
  case MotionNotify:
  case XKeyPress:
  case XKeyRelease:
  case EnterNotify:
  case LeaveNotify:
    d->queuedUserInputEvents.append(event);
    continue;
  // ...
可见我们需要看看 QEventDispatcherX11Private 维护的 queuedUserInputEvents 队列是如何被处理的,
class QEventDispatcherX11Private : public QEventDispatcherUNIXPrivate
{
    Q_DECLARE_PUBLIC(QEventDispatcherX11)
public:
    inline QEventDispatcherX11Private()
        : xfd(-1)
    { }
    int xfd;
    QList<XEvent> queuedUserInputEvents;
};
这是一个链表,事实上 QApplication 调用 processEvents() 时,即调用了 QEventDispatcher::processEvents()。这只是处理消息的函数,我们仍然不清楚该函数如何被调用的,在 QCoreApplication::exec() 里,另外一个东西就是 QEventLoop,在 QEventLoop::exec() 里面我们找到了答案,
// remove posted quit events when entering a new event loop
if (qApp->thread() == thread())
  QCoreApplication::removePostedEvents(qApp, QEvent::Quit);

while (!d->exit)
  processEvents(flags | WaitForMoreEvents | EventLoopExec);
这就是核心的部分。

上面的过程比较混乱,这里重新总结下,建立的 QCoreApplication/QApplication 建立了一个 QEventDispatcher,然后建立了用户界面后就可以响应用户输入了,调用了 QApplication::exec() 后,这部分 X event 通过 Xlib 发送过来,由 QEventLoop 处理消息,调用的是 QEventDispatcher::processEvents() 维护消息队列,该函数会通过 QApplication::x11ProcessEvent() 将消息发送给对应的 QWidget,也可以通过设置用户自己处理 XEvent,这会发送给那个 QWidget 对应的 x11Event() 函数处理。

这也就是为什么写多线程程序时,如果希望在新的线程使用消息机制,也需要在 QThread::run() 里面调用 QThread::exec() 维护消息队列。

42 comments:

Anonymous said...

Spoommatani
モンクレール店舗
Woolrich Outlet
Cheap Beats by Dre
シャネル バッグ
dr dre beats

[url=http://www.bennynato-onlus.org/public/allegati/Cheap-Monster-Beats.html]beats by dre[/url]
[url=http://thermoplastictrading.com/Cheap-Monster-Beats.html]beats by dre[/url]
[url=http://www.prioryvale.net/Monster-Beat.html]dr dre beats[/url]
[url=http://www.bennynato-onlus.org/public/allegati/Monster-Beat.html]Beats by Dre UK[/url]
[url=http://www.woolrichforyou.com/]Outlet Woolrich[/url]

http://thermoplastictrading.com/Cheap-Monster-Beats.html beats by dre
http://www.woolrichv.com/ Outlet Woolrich
http://www.prioryvale.net/Monster-Beats.html beats by dre uk
http://www.straievil.com/netoraji/upload/handbag.html シャネル ウォレット
http://www.woolricha.com/ Woolrich Parka

Orgargegava
アグ
ugg ブーツ
woolrich bambino
woolrich outlet
ugg ブーツ

http://www.outletbootsofficials.com/ ugg
http://www.thebestforjp.com/ アグ
http://www.snowbootstoyou.com/ uggブーツ
http://www.timber-landforjp.com/ ティンバーランド チャッカブーツ
http://www.prioryvale.net/beatsbydre.html dr dre beats

[url=http://www.straievil.com/netoraji/upload/moncler.html]モンクレール店舗[/url]
[url=http://www.ilovetheboots.com/]アグアウトレット[/url]
[url=http://www.annksnowboots.com/]UGG[/url]
[url=http://www.woolrichc.com/]woolrich italia[/url]
[url=http://www.thenewestbootsforyou.com/]ugg[/url]

Anonymous said...

Hello. And Bye. Thank you very much.

Anonymous said...

on avait etudie avec soin les causes qui, viagra pfizer, les acides monoatomiques ou monobasiques como son la actualizacion de las referencias a cialis super active, millones de personas derivada de esos privilegios, E noto da tempo come in alcuni Imenomiceti, viagra pfizer, ben visibili ad occhio nudo, aber sich nicht heller rothet, cialis bestellen deutschland, Das Destillat besteht aus Aether,

Anonymous said...

Hello! I realize this is kind of off-topic however I needed to ask.
Does building a well-established blog such as yours
take a large amount of work? I'm completely new to writing a blog but I do write in my journal daily. I'd
like to start a blog so I can share my own experience and views online.
Please let me know if you have any kind of suggestions
or tips for brand new aspiring bloggers. Appreciate it!


My web site :: tumblr.com

Anonymous said...

When someone writes an post he/she maintains the thought of a user in his/her mind that how a user can be aware of it.
Thus that's why this article is amazing. Thanks!

My site :: monster beats

Anonymous said...

If some one desires to be updated with latest technologies after that he must be visit this web page and be up to date all the time.


Also visit my web blog: モンスター ヘッドホン

Anonymous said...

Very good post. I definitely appreciate this website.
Keep it up!

Also visit my website - モンスターケーブル

Anonymous said...

Wonderful beat ! I wish to apprentice at
the same time as you amend your web site, how could i subscribe for a
blog web site? The account helped me a appropriate deal.
I had been a little bit familiar of this your broadcast offered vivid clear
concept

Visit my web-site - ルブタン シューズ

Anonymous said...

WOW just what I was searching for. Came here by searching
for ジョーダン

My page: air jordan

Anonymous said...

Hey there! This is my first comment here so I just wanted to
give a quick shout out and tell you I truly enjoy reading through your articles.
Can you suggest any other blogs/websites/forums that deal with the same topics?
Thanks!

Here is my blog post :: chloe バッグ

Anonymous said...

What's up, just wanted to say, I liked this article. It was helpful. Keep on posting!

Feel free to surf to my web page - トリーバーチバッグ

Anonymous said...

Wow that was strange. I just wrote an extremely long comment but after I clicked submit my comment
didn't appear. Grrrr... well I'm not writing all that over again.
Anyway, just wanted to say excellent blog!

Here is my web-site; モンスタービート

Anonymous said...

It's appropriate time to make some plans for the future and it's
time to be happy. I have read this post and if I could I want to suggest you some interesting things or advice.
Maybe you can write next articles referring to this article.
I want to read more things about it!

My web-site; http://www.miumiuoutletshop2013.com/

Anonymous said...

Great site you've got here.. It's difficult to find excellent writing like yours nowadays.
I truly appreciate people like you! Take care!

!

Review my homepage :: http://bracarae.com/wiki/index.php?title=Utilizador:GloriaIrb

Anonymous said...

Wonderful blog! I found it while browsing on Yahoo News.

Do you have any tips on how to get listed in Yahoo News?

I've been trying for a while but I never seem to get there! Appreciate it

Here is my webpage - クリスチャンルブタン靴

Anonymous said...

Hi there would you mind sharing which blog platform
you're working with? I'm looking to start my own blog soon but I'm having a difficult time choosing between BlogEngine/Wordpress/B2evolution and Drupal. The reason I ask is because your design seems different then most blogs and I'm looking for something completely unique.

P.S My apologies for getting off-topic but I had to ask!

Here is my page :: 財布トリーバーチ

Anonymous said...

This is my first time pay a quick visit at here and i am in fact impressed to read everthing at
single place.

Stop by my blog; ジョーダン

Anonymous said...

I think that is among the most important info for
me. And i'm happy studying your article. However want to observation on some common things, The web site style is perfect, the articles is really great : D. Excellent process, cheers

Here is my blog; ルイヴィトン財布

Anonymous said...

Hi there! Do you use Twitter? I'd like to follow you if that would be okay. I'm undoubtedly
enjoying your blog and look forward to new posts.

Also visit my site: オークリー

Anonymous said...

I think the admin of this web page is actually working hard in
support of his site, since here every material
is quality based data.

Here is my site - prada バッグ

Anonymous said...

Greetings! Very useful advice within this
article! It is the little changes that will make the most significant changes.

Many thanks for sharing!

Have a look at my web site :: エアジョーダン

Anonymous said...

hello there and thank you for your information – I have certainly picked up something new from
right here. I did however expertise some technical issues
using this website, as I experienced to reload the site many times previous to I could get it to
load properly. I had been wondering if your web hosting is OK?
Not that I am complaining, but slow loading instances times will often affect your placement in google and can damage your quality score if ads and marketing
with Adwords. Anyway I am adding this RSS to my email and can look out for a lot more of your respective fascinating content.

Ensure that you update this again very soon.

my site monster ヘッドホン

Anonymous said...

Does your site have a contact page? I'm having a tough time locating it but, I'd like to send you an
email. I've got some suggestions for your blog you might be interested in hearing. Either way, great site and I look forward to seeing it expand over time.

Here is my blog ... モンスタービート

Anonymous said...

Terrific article! This is the type of info that are
meant to be shared across the internet. Disgrace on the seek engines for not positioning this submit upper!
Come on over and discuss with my web site .
Thanks =)

My webpage - エアジョーダン

Anonymous said...

Hello, after reading this amazing post i am also delighted to
share my know-how here with friends.

Look into my weblog :: アバクロンビー

Anonymous said...

I blog often and I genuinely thank you for your content.

This article has really peaked my interest.

I'm going to book mark your blog and keep checking for new details about once per week. I subscribed to your RSS feed too.

my blog: ロレックスレプリカ

Anonymous said...

I couldn't refrain from commenting. Well written!

Also visit my web site ジョーダン

Anonymous said...

Hmm is anyone else encountering problems with the images
on this blog loading? I'm trying to find out if its a problem on my end or if it's
the blog. Any feed-back would be greatly appreciated.


My blog - グッチ バッグ

Anonymous said...

Way cool! Some extremely valid points! I appreciate you writing this post
and also the rest of the website is really good.



My page; ロレックスレプリカ

Anonymous said...

Hello to every body, it's my first go to see of this web site; this web site carries amazing and actually fine stuff in support of readers.

Here is my homepage :: シャネルトートバッグ

Anonymous said...

Magnificent beat ! I wish to apprentice while you amend your site, how
could i subscribe for a blog web site? The account aided
me a acceptable deal. I had been a little bit acquainted of this your
broadcast provided bright clear idea

Also visit my blog :: http://www.monsterbeatsheadphoneoutletsale.com

Anonymous said...

I visit every day some web sites and sites to read posts,
however this web site presents feature based posts.

Feel free to surf to my web page ... louisvuittonhandbagsoutletssale.com

Anonymous said...

Great website. A lot of helpful info here.
I am sending it to several pals ans also sharing in delicious.
And certainly, thanks on your effort!

Feel free to visit my weblog; シャネルバッグ

Anonymous said...

Everyone loves it when folks come together and
share thoughts. Great blog, continue the good work!

Also visit my web blog; シャネル アウトレット

Anonymous said...

Keep on working, great job!

Also visit my webpage ... サングラス オークリー

Anonymous said...

I'm really enjoying the design and layout of your blog. It's a very easy on the eyes which makes it
much more enjoyable for me to come here and visit more often.

Did you hire out a developer to create your theme?

Excellent work!

Look at my web site: アバクロンビーフィッチtシャツ

Anonymous said...

An outstanding share! I've just forwarded this onto a co-worker who has been doing a little homework on this. And he actually ordered me dinner because I stumbled upon it for him... lol. So allow me to reword this.... Thank YOU for the meal!! But yeah, thanx for spending the time to discuss this subject here on your site.

my webpage; ロレックスコピー

Anonymous said...

This website was... how do you say it? Relevant!
! Finally I've found something that helped me. Thanks a lot!

my blog エアジョーダン通販

Anonymous said...

Everything is very open with a precise description
of the issues. It was truly informative. Your site is very useful.
Many thanks for sharing!

Here is my web site - Vuitton 財布

Anonymous said...

Have you ever considered creating an ebook or guest authoring on other sites?
I have a blog centered on the same topics you discuss and would really
like to have you share some stories/information. I know my subscribers would
value your work. If you are even remotely interested, feel free to shoot me an e-mail.


my blog - monster beats

Anonymous said...

If you are going for finest contents like I do, simply visit this
web page everyday as it presents quality contents, thanks

my weblog: サングラスレイバン

Anonymous said...

Hi this is kind of of off topic but I was wanting to know if blogs use WYSIWYG
editors or if you have to manually code with HTML. I'm starting a blog soon but have no coding experience so I wanted to get guidance from someone with experience. Any help would be greatly appreciated!

my site; ヴィトン 長財布