To Infinity And Beyond
About - MoCap SMPL-X priors - NeRF Rendering System - Problems - References
About
With more and more AR and VR devices becoming ubiquitous and advancement in animation the animation, the difference between virtual and reality are getting blurred. This makes perception of reality and rendering it along with virtual scenes as the core problems. Being interested application of AI/ML in the area of 3D graphics and animation and having a background in video encoding for conferencing, transmission am working on two problems (a) Motion Capture from monocular videos dealing in perception and (b) Neural rendering of rigid and non-rigid bodies dealing in rendering.
Further, the current advancements in deep learning in the area of GAN, Implicit representations, Transformers, GCN make them a invaluble tool that aid in solving these core problems. Anyone interested in the following problems can reach me<EMAIL_ADDRESS>Motion Capture using SMPL-X priors (details)
- Using monocular video information
- Facial, finger and full Body pose extraction
Neural radiance field rendering systems (details)
- Fast training for rigid bodies
- Non-rigid (human models) pose, cloth and hair feature transfer
Problems Working On
- Shape and pose iteration for refinement of image based pose for the original dimension link
- HMR (Human mesh recovery) use CNNs and so the images are resized thus losing its prediction precision.
- SMPLify-X based approches are iterative and do not reach global minima faster
- A hybrid approach which merges the both to get higher precision prediction while maintaining consistency across frames
- Multiresolution video pose estimation
- A video has a large number of images and estimating pose for all frames would be huge
- Pose interpolation using transformers to reduce computation
- Transformer based approaches to use temporal consistency to get better prediction for occluded parts
- Identify non occluded frames and interpolate intermediate frames to estimate pose
- Learning pose using videos in the wild
- Use 2D keypoint markers and temporal shape consistency to learn mocap information
- Estimate facial and finger pose estimation
- Estimate initial prediction using resized input images using neural network based approaches
- Apply SMPLify-X based iterative approaches to refine pose using full resolution images to get precise prediction
- Facial, hand and full pose control of deformable human neural avatars
- Extract mocap information from driver video
- Learn neural body based avatars using SMPL-X
- Deform SMPL-X model using the driver video
- Deformable neural cloth and hair styles extraction from video in wild
- Use human parser to extract different clothing types and hair
- Learn neural models for each segment extracted earlier
- This helps in transfering information across different avatars
- Multi-resolution neural training for both rigid and non-rigid objects
- Active learing based appraches to identify subset of images which maximize learning
- Start with low resolution images and downsampled video
- Choose the training subset based on the rendered quality across different view
- Voxel based latent learning link
- Learn a pre-trained network which approximates simpler shapes ata voxel level
- Reduce training iteration time
- Neural sub-problems
- Predicting occluded regions from known regions
- GAN based generator for neural body
References:
- VIBE: Video Inference for Human Body Pose and Shape Estimation
- SMPLify-X, SMPL-X, SMPL
- FrankMocap: A Strong and Easy-to-use Single View 3D Hand+Body Pose Estimator
- End-to-end Recovery of Human Shape and Pose, SPIN: SMPL oPtimization IN the loop
- Illustrated Transformer
- NeRF: Neural Radiance Fields
- Neural Body: Implicit Neural Representations with Structured Latent Codes for Novel View Synthesis of Dynamic Humans
- KiloNeRF: Speeding up Neural Radiance Fields with Thousands of Tiny MLP
- Neural Sparse Voxel Fields (NSVF)
- Controllable Person Image Synthesis with Attribute-Decomposed GAN
- PIFuHD: Multi-Level Pixel-Aligned Implicit Function for High-Resolution 3D Human Digitization (CVPR 2020)
- Debugging networks
- On the Continuity of Rotation Representations in Neural Networks, Tutorial blog


SF Is_Space
Checks to see if the character is white-space character.
Return Integer = SF Is_Space( String, Integer )
String
The source string to check.
Integer
The position in the string to check.
Returns 1 if the character is a white-space character. Returns 0 if the character is not a white-space character.
Error Codes: -1 (Null string), -2 (Index out of bounds)
Checks to see if the character is a white-space character.
The following white-space characters includes...
- Space (0x20)
- Horizontal Tab (0x09)
- Newline (0x0A)
- Vertical Tab (0x0B)
- Feed (0x0C)
- Carriage Return (0x0D)
#Constant CRLF Chr$(0x0D) + Chr$(0x0A)
Rem Or you can use Crlf$() command from Matrix1 Utility Plug-in.
String$ = "3..." + CRLF + "2..." + CRLF + "1... " + CRLF + "0!"
For X = 1 To Len(String$)
If SF Is_Space(String$,X) = 1
Inc Space_Count
Else
Inc Non_Space_Count
EndIf
Next X
Print "String evaluated = " + String$
Print
Print
Print
Print
Print "This string has " + Str$(Space_Count) + " Space characters."
Print "Non Space characters = " + Str$(Non_Space_Count)
Wait Key
String Functions Index
Main Menu


Math and Helper Functions
Absolute Offset getButtonAction disable_gui enable_gui is_gui_disabled GlobalCondition GetLucasSavegameListBox InitGuiLanguage getInteger clearToSpace
Absolute
int Absolute(int value);
Returns the absolute value of a given value.
Offset
int Offset(int point1, int point2);
Returns the offset between to two given values.
getButtonAction
int getButtonAction(int action);
Returns the connected action of a verb button. The actions for the verb buttons are not “hard-wired” inside the GUI-script, but defined in the function SetButtonAction.
See also: SetActionButtons, AdjustLanguage
disable_gui
function disable_gui();
This functions disables the GUI and hides it.
See also: is_gui_disabled, enable_gui
enable_gui
function enable_gui();
This function enables the GUI again.
See also: is_gui_disabled, disable_gui
is_gui_disabled
bool is_gui_disabled();
Returns true, if the GUI is currently disabled, false otherwise
See also: disable_gui
GlobalCondition
int GlobalCondition(int parameter);
Used to check for conditions that are used many times in the script. For example, it’s used to check, if the mouse cursor is in the inventory and the mode walk or pickup are selected. Returns 1, if the condition is true and 0 otherwise.
GetLucasSavegameListBox
function GetLucasSavegameListBox(ListBox*lb);
This is a helper function to initialize the save and restore dialogs.
InitGuiLanguage
function InitGuiLanguage();
This is a helper function to set the correct sprites for the verb GUI.
getInteger
int getInteger();
This function returns the first integer value of the internal variable “numbers” and calls the function clearToSpace to overwrite that number with blank characters.
See also: clearToSpace
clearToSpace
String clearToSpace(String text);
This function overwrites the first value or word from the given string with blank characters. Afterwards the new string is being returned.
See also: getInteger
Unhandled Events
In order to give a the player a feedback for actions the author hasn’t thought of, unhandled events come into play. With a single function, you can achieve something like “That doesn’t work” or “I can’t pull that”, which makes a game much more authentic and alive.
Unhandled
function Unhandled(int door_script);
Use this function at the end of your any_click functions in order to cause default reactions. For example:
function cChar_AnyClick()
{
if (UsedAction(eGA_LookAt)) player.Say("He looks like he is hungry.");
else Unhandled();
}
In this example, you get a default reaction for everything but look at. The optional parameter is only used internally to make the function work with the door scripts.


{% extends "skeleton/_body.html" %} {% hyde title: "Social Favorites" created: 2011-11-17 14:30:00 listing: False %} {% block content_body %}
I got very swept up in the Web 2.0 and gave most of the new services a try. Many of these services didn't have staying power for me but a few of them worked their way into my daily routine. Here they are:


A verifiable claim is a qualification, achievement, quality, or piece of information about an entity's background such as a name, government ID, payment provider, home address, or university degree. The use cases outlined here are provided in order to make progress toward possible future standardization and interoperability of both low and high-stakes claims with the goals of storing, transmitting, and receiving digitally verifiable proof of qualifications and achievements. The following use cases focus on concrete scenarios that the technology created by the group should address.
This document is an early version being used as an integration point for a variety of use cases assembled from throughout the industry. As the document becomes more mature this status will be updated accordingly.
The Verifiable Claims Task Force at the W3C is investigating the requirements around secure, verifiable, and richly descriptive "claims". The goal of the Task Force is to determine if there is a sufficient understanding and need to merit the creation of a W3C Working Group to develop Recommendations in this space.
People need to make many kinds of claims as part of their everyday lives. As more important business moves to the Internet, people need to be able to transmit instantly verifiable claims about their accomplishments and qualifications. From educational records to payment account access, the next generation of web applications will authorize users to perform actions based on rich sets of credentials issued by trusted parties. Human-mediated decisions about job applications, collaboration and professional development will depend on filtering and analyzing growing amounts of data about individuals' experience and accomplishments.
Standardization of digital claim technologies makes it possible for many stakeholders to issue, earn, and trust these essential records about their counterparties, without being locked into proprietary platforms.
This document is organized around the basic operations that might be performed on a Verifiable Claim. For each of these operations, and for the additional section "Uncategorized / General", the document captures some high level use cases grouped by the requirement they represent. Each use case contains information about its motivation, relative priority, and one or more examples to help define the target beneficiaries of its support.
Just to provide a basis for discussion, this section illustrates a simple example of how a claim might be used in a typical commerce situation. Please remember that it is just an example, and should not be thought of as the canonical way such a system must be implemented. First, consider this diagram:
Each use case in this section should have a unique human assigned identifier that starts with "uc". The example use case (in the source below, commented out), which everyone should feel free to use a template, has the id "uc-example". In order to disambiguate, please ensure that the subsection is added into the prefix (e.g., uc-issuing-my-new-use-case). Also, please use hyphens instead of camel case.
Credential Operations
Issuing
Issuer Advertises Credential Template / aBadge Class
The Issuer publishes a Credential Template / Badge elaborating on the requirements that must be completed to issue the credential.
Recipient Proves Suitability for Credential
A recipient proves that they have met the requirements necessary to acquire the credential from the issuer.
Issuer Issues Credential to Recipient
The issuer customizes the credential template / badge for a particular recipient. The credential/badge may be digitally signed.
Recipient Stores Credential
The recipient stores the credential in a credential vault or other long-term storage location.
Revoking
Issuer Revokes Credential
An issuer revokes a previously issued credential, after which it will no longer pass verification procedures.
Consuming
Credential Consumer Requests Credential
A credential consumer application requests that a recipient provide one or more credentials.
Recipient Authorizes Credential Transmission
The recipient authorizes the transmission of the credential(s).
Credential Consumer Verifies Credential
The Credential Consumer verifies that the credentials are valid.
Credential Consumer Grants Access to Recipient
The credential consumer grants the recipient access to a resource after verifying the credential.
Managing and Sharing
Recipient Authorizes a Credential to be Read Asynchronously
The recipient pre-authorizes a credential consumer to access a particular type of credential on a periodic basis.
Recipient Displays Credentials to Various Entities Based on an Access Control List
The recipient authorizes access to view/pull credentials to particular entities based on an access control list.
Recipient Displays Credentials on the Web and through Social Media
The recipient enables her credentials to be publicly viewable on the web and through social media without access lists.
Endorsing
Recipient Collects Counter-signatures for Credential
A recipient collects counter-signatures on a credential, reinforcing the credential’s authenticity.
Credential Operations in Detail
Issuing
Issuer Advertises Credential Template / Badge
Metadata
There are important pieces of metadata associated with a particular Credential / Badge:
Colorado State University is creating several recognition certificates to help foster a campus culture of leadership, tolerance and acceptance. The dean’s office defines the criteria and what evidence is accepted to prove that the recipient has met the criteria.
Green Federal Credit Union has performed Know Your Customer clearing (driver’s license, background check, anti-money laundering blackslist check, etc.), on Reece and would like to issue a credential to him for use at other financial institutions.
Harper High School teachers define soft skill credentials to award their students, using a web app that has badge defining and issuing features.
The Veterans Affairs office is working on an initiative to translate military experience into digitized claims of the veteran’s skills to help veterans better connect with employment when they return from duty.
The Project Management Institute which has been issuing Project Management certificates for many years is moving toward digitization of their existing certification program.
Motivation
The credential definition includes descriptive metadata about the circumstances and context in which the badge is issued to the recipient. The issuer clearly defines this information so others who later view or review the credential can understand the context behind it.
Publishing Requirements
An employer requires a specific technical certification on a job posting in order to ensure that the candidates will be experienced with the equipment to be used on the job.
A school district posts the requirements for credentials from out-of-school learning programs to be accepted for school credit so that summer camp administrators know how to make sure their program counts.
A college course lists certain credentials as prerequisites, so that students know how to plan out their academic year to be able to enroll in the course.
An employer lays out a map of specific credential classes as a training plan for new employees, so that the employees and their supervisors can track and evaluate their progress.
Motivation
Consumers may publish requirements for credentials that qualify recipients for particular opportunities from the consumer.
Vocabularies
Education credentials use a common set of vocabularies to establish a credential type, alignment, and criteria.
Healthcare credentials use a common set of terminology to express licensing status, prescription writing authorization, and which medical facilities the recipient has access to enter.
Anti-money laundering credentials can be used to report suspicious activity on a global basis by using a common set of terminology to express people and organizations that are engaged in transactions.
Motivation
The interoperability of credentials depends largely on market verticals defining and standardizing common terminology in publicly available machine-readable vocabulary documents.
Recipient Earns Credential
Testing
Sally takes the GRE.
Motivation
The results of tests could be shared more easily if they were produced in the form of a digital credential.
Byproduct of Action
Pele attends the EduConf 2015 conference.
Motivation
Credentials should be able to be issued as a side-effect of performing a particular real-world action.
Issuer Issues Credential to Recipient
Claims
An issuer can make a variety of claims about a recipient:
A teacher professional development association awards Penny Chen a digital certificate which claims she has fulfilled her professional development units and has demonstrated mastery over common core instruction.
Brian is taking an online course on web development. When he completes modules, the website issues badges to him for module completion and progress through the course. At the end of the course he has an option to submit his work and quizzes that are evaluated and then he is issued a badge.
The state government of California issues Amari a driver’s license after he passes both the written and practice driving tests.
Educause conference issues digital badges to all conference speakers through a claim code system. Conference speakers are given a special code, that they input on the educause site which triggers a badge to be issued to them.
Motivation
An issuer can make a claim that asserts something specific about the recipient, such as a qualification, attribute, or the attainment of a particular defined achievement.
Security
It is important that an issuer ensure that a recipient is who they say they are before issuing important credentials to the recipient.
Privacy
Personally identifiable information must use known data fields in order to enable credential curation services to protect the recipient’s privacy.
Accessibility
A credential must be able to be issued to people that have disabilities (10% of the human population)
Exceptions
A recipient may not have a way to store credentials.
Bearer Credentials
Niambo would like to prove that she is over the age of 13 to get access to a protected website. She has a proof of age credential that can be used in a pseudo-anonymous fashion. She proves her age pseudo-anonymously, as the credential consumer website does not want to track its users, but does want to ensure that it is compliant from a regulatory perspective.
Motivation
It should be possible to prove that you have a particular attribute without leaking personally identifiable information.
Privacy
Two colluding websites should not be able to collude and build a more accurate profile of a person. There are many problems with this privacy requirement. Namely, the Open Web Platform provides multiple mechanisms like session tracking, supercookies, and email-based identifiers, that enable colluding websites to track their users across the Web. Given these existing tracking mechanisms, a bearer credential solution shouldn’t make the problem worse.
Self-claims
Mandy has years of experience as a web developer but as an autodidact, doesn’t have the credentials to prove it when applying for jobs. Mandy issues herself a credential and includes information/evidence to support her claim.
Motivation
A recipient should be able to make a claim that asserts something specific about herself, such as a qualification, attribute, or the attainment of a particular defined achievement.
Identifier Aliasing
One entity may have multiple identities that need to be tied together:
Owen received a number of credentials issued to an employment-based identifier and uses an identifier equivalence credential issued by his employer to bundle these together with credentials issued to a personal identifier so that consumers will trust the different credentials were issued to the same recipient.
Sally was issued a credential from her former high school to her then school email<EMAIL_ADDRESS>Sally has since transferred to a new high school and wants to be able to claim that credential still as hers even if her former high school email is no longer valid.
When Jabar was 12, he took several online courses on Khan Academy using his parent’s or teacher’s emails, due to COPPA regulations that didn’t allow him to create his own account. During that period he earned various badges and certificates which, now that he’s 13, he’d like to claim under his own email address.
Motivation
A recipient may collect credentials asserting that multiple identifiers correspond to their identity so that they may present credentials issued to several of these identifiers at once, as long as the consumer of that statement trusts each of the equivalence credential issuers.
A recipient must be able to claim credentials issued to different identifiers owned by the recipient.
Security
When sharing email accounts, forging credentials becomes easier/more commonplace. There are also accidental information leakage issues w/ shared credentials.
Recipient Stores Credential
Credential Storage
A recipient of a digital credential may store it on a variety of platforms or media:
Mayumi has earned credentials from many different issuing organizations including her college, online courses, social engagement platforms, etc. She is able to collect all these badges in one place on an online badge management and storage service. She is also able to use different services to manage her badges as she chooses.
Liam saves all of his credentials on his laptop. He likes to have them there so that he knows where they all are and can upload them to various applications or send in emails.
Sammie earns credentials for every book she’s read in her reading club. Her credentials are downloaded to an app on her ipad which gives her discounts on purchases of future books.
Motivation
A recipient of a digital credential may store it on a variety of platforms or media. Credentials must be portable.
Revoking
Issuer Revokes Credential
Consuming
Credential Consumer Requests Credential
Interactive Request
Roxy visits the FineWines.com website and selects a number of wines to purchase. The website requests a proof-of-age and shipping address credential from Roxy. Roxy's IronVaultCorp credential service delivers both credentials, allowing her to finalize the transaction.
A bank would like to perform "Know Your Customer" clearing on a new customer by checking to see that they are a citizen of Finland and that they have a current national ID card issued to them by their government.
Jorge reads an article on BreakingNews.com and wants to engage in a discussion in the comments section. The website requests a verified email address credential to log him into the site. Jorge’s credential service delivers the credential, authorizing him to start posting comments.
Mona sends an international/wire transfer that requests credentials for both the sender and receiver, greatly reducing the risk for the remittance by manually mis-keying the source and destination of the funds.
Josie is a healthcare worker that has created a profile on a professional social network to make herself readily available for new opportunities in the workforce. She lists her employment history and credentials including degrees, certificates and digital badges. The website requests verification of her credential claims in order for her credentials to post. The website pings various credential vaults in which Josie stores her credentials and verifies them before allowing Josie to post them.
Seraph initiates a transfer of $45,000 USD to her parents in Pakistan. She is asked to provide a credential used during the high-value transfer, further demonstrating that the correct person is authorizing the transfer.
Janet visits SamanthasClub.com, and wants to view the member-only section of the site. The website requests her membership credential, which she provides. The website confirms her membership credential is valid and grants her access to the member-only portion of the site.
Motivation
A requestor may request to view credentials from a credential service that stores them. The service forwards the request to the credential recipient, who interactively authorizes transmission of some or all of the requested credentials to the requestor.
Basic website login can be implemented using a credential.
Legacy Support
Petra goes to login to a website, but does not have any credentials. She does, however, have a username/password based account on the website. She is able to bypass the credential-based login and use a username/password login instead.
Motivation
Transition from username/password to credentials-based access will take years and some sites may never transition to credentials-based access. It’s important to continue to support username/password-based login for legacy sites.
Recipient Authorizes Credential Transmission
Recipient-initiated Transmission
Umal wants to buy a PG-13 movie from an online retailer that requires proof of age. He provides a credential stating that he is over the age of 13 from an issuer that the store trusts. This enables the online retailer to avoid collecting information on a minor while ensuring that the proper age check is performed before granting him access to the movie.
Marcus uploads a collection of badges he’s earned from several summer programs as part of an application for a summer camp counselor job. He chooses credentials that showcase his experience with relevant subject matter and competencies. The decision about who to hire for the job is too complex for a computer, so a camp administrator reviews Marcus’s application and considers the credentials’ applicability.
Motivation
A credential recipient may upload one or more credentials to a consumer service or transmit credentials by email in order to apply to access an opportunity or service. The request may be evaluated by an automated system or by a human adjudicator.
Social Sharing
Chiara, who is seeking new career opportunities, wants to share a list of her credentials with a recruiter. She takes her credentials from her desktop and includes them as an attachment to an email she sends the recruiter. The badges retain their integrity and content.
Beaver is thrilled to have earned the Associated Student Board Leader of the Year commendation. He wants to shout it from the rooftops and accordingly shares it on his various social media accounts including Facebook, Twitter and LinkedIn.
Motivation
A recipient of a digital credential may choose to share their credential through a variety of mediums, whether email, embed or social media.
Data Rights
Rosa is transmitting her email address to a group buying website and wants to ensure that her email address will not be used for unsolicited emails. She attaches a "no advertising" assertion to her email credential to ensure that it isn't re-transmitted to 3rd parties for advertising purposes.
Motivation
A recipient of a digital credential may choose to include information that asserts what their information may be used for.
Composability
Credentials may be displayed together in order to meet complex requirements:
Marisol wants to open a bank account at a new bank. The bank requires two valid forms of identification. She uses a US Passport credential and a Colorado driver’s license credential to prove that she is who she says she is to the bank.
Willie is transferring between universities and wants to ensure he gets credit for work he did at his old school, so he bundles the credentials he received for his course work with a 3rd party’s endorsements that he knows the new school trusts, so that the new school is more likely to accept the credentials.
Idris wants to take the introduction to organic chemistry which is an upper division course. In order to qualify for that course, Idris needs to have proven that he’s taken Biochemistry and Physics. He proves that he’s taken these prerequisite courses which unlocks the opportunity to enroll in the organic chemistry course.
Motivation
Credentials may be displayed together in order to meet complex requirements or prove qualification more substantively than would be possible with one credential alone.
Credential Consumer Verifies a digital credential may verify that the credential is an authentic statement of an issuer’s claims about the recipient. The verifying entity must have the capability to connect the issuer’s identity to its credential identifier and the recipient’s identity to their identifier as indicated in the credential. The issuer’s verification information, such as its public key, must be discoverable from the credential record and verifiably linked to the issuer.
Pseudo-anonymity
June goes to her local beer and wine store to buy a bottle of wine. She submits her identity credential that lets the liquor store owner know that she is over 21 without having to reveal her actual DOB.
A credential contains an identifier that is a hash of a known identifier (email address) of an individual so that those who know the recipient identifier can verify the credential, but those who don’t know the identifier cannot derive personally identifiable information about the recipient.
Motivation
Credentials may be issued to an identifier such that it is possible for the recipient to prove that the identifier corresponds to them without revealing personally identifiable information. In the case of a subpoena, an identity service may be compelled to reveal additional information beyond what the holder of the identity wished to transmit.
Credential Consumer Grants Access to Recipient
Searchability
Steve, an HR recruiter searches his database of job-seekers for a position that requires a particular defined credential.Steve narrows a list of candidates to those who have a valid passport credential.
Motivation
A credential consumer who has been presented credentials from a large number of candidates can sort and filter those candidates by credentials they have received and claims made by those credentials.
Managing
Recipient Authorizes a Credential to be Read Asynchronously
Non-interactive Transmission
When performing straight-through-processing, a correspondent banking client would like to prove proper “Know Your Customer” (KYC) clearing of the transaction by including the KYC credentials for the sender and receiver of the transaction.
A grocery store wants to send out a product recall notice and requests an up-to-date email address from each of their customers' credential service to ensure that they're sending it to the correct email address. Mary has previously authorized the store for ongoing access to one of her verified email address credentials, so this credential is transmitted without bothering Mary with an interactive authorization request.
Calvin applies for a job at a biotech company. He authorizes the job service acting on behalf of the biotech company to access his verified undergrad and grad school credentials along with his digital badges which he’s curated for the company to review that he thinks exemplifies his work, experiences and qualifications for the job. This collection of credentials are transmitted to the job service and used as a way to automate the initial screening of applicants.
Jackie allows TrustMart to automatically retrieve her latest address and phone credentials. She then receives unsolicited junkmail that she knows came from TrustMart. She deauthorizes TrustMart from pulling her latest address and phone credentials.
Motivation
A credential recipient may pre-authorize the public or specific requestors to access certain credentials through a credential service.
Recipient Displays Credentials to Various Entities Based on an Access Control List
Portability
A recipient moves their credential between different storage locations, without losing the ability to transmit or authenticate it:
Amy stores her credentials on a local hard drive, then later wants to upload them to a resume-building service for sharing with prospective employers.
When Bruce graduates from college, he moves his credentials from the university’s credential store to a different service.
Charlie would like to make a backup of his credentials by storing them on a second credential vault service.
When transferring to UCLA, harice is able to also transfer her lower division credits from Santa Monica College to UCLA’s credential store.
Motivation
A recipient moves their credential between different storage locations, without losing the ability to transmit or authenticate it.
Repudiability
Credential recipients should have the ability to repudiate any credential issued to them:
Rosa works with a community support worker at a public-access credentialing service to get a credential publicly “doxxing” her by listing her home address taken down to protect her safety.
Marie disputes the validity of a credential making claims about her and publishes a verifiable repudiation of that credential.
Motivation
Credential recipients should have the ability to repudiate any credential issued to them, which could take the form of takedown requests to platforms where harmful, or misleading information about them is available.
Privacy
Credential Service must establish a takedown request procedure
Endorsing
Recipient Collects Counter-signatures for Credential
Endorsement
Two people get married and get a marriage credential which needs to be digitally signed by the person that married them and the witness, in that order. The credential is first issued by the person that married them, and is then counter-signed by the witness.
MidBank is attempting to establish a solid credit rating and hires three credit ratings agencies to audit its books. Each firm determines that the bank should have a AA credit rating and digitally countersigns the same credential 3 times to demonstrate the credit worthiness of the bank.
Olivia is choosing among summer internships, some of which offer opportunities to earn badges that are endorsed by her school. These are badges that could be used to fulfill an interest-driven learning graduation requirement her district has recently implemented. With the additional information provided to her by the school’s endorsement of certain badges, her choice among internships is made much simpler. This example came from the Open Badges Endorsement Framework Working Paper, which was created by the Badge Alliance Endorsement Working Group.
Motivation
Parties other than a credential’s issuer may be able to add value for certain consumers by endorsing it. An individual recipient’s credential may be endorsed in order for a third party to strengthen the claims it makes about that recipient. A defined credential class may be endorsed by a consumer or other outside entity in order to extend trust to the recipients of that credential among consumer entities who trust the endorser.
Endorsement on self-claims
After Mandy issues herself a credential with the supporting evidence and information, she reaches out to her previous clients including various sized organizations for which she’s done development work requesting they endorse the self-issued credential. Several organizations oblige and endorse the credential.
Motivation
An organization or individual can endorse a self-made claim by a recipient that asserts something specific about herself, such as a qualification, attribute, or the attainment of a particular defined achievement.
The editor is thankful to the following contributions from the Web Payments Workshop, the Web Payments Community Group, and the Credentials Community Group, specifically (in alphabetical order): TBD


Book-A-Meal
Sign In
Sign Up
Having issues with your password ?
Enter your email below so we can send you a reset link
Email Address


Class for Zend\View\Model\ConsoleModel to help enforce private constructs.
Note: all private variables in this class are prefixed with "__". This is to mark them as part of the internal implementation, and thus prevent conflict with variables injected into the renderer.
| package |
Default |
|---|
__construct(array $config = array())
| todo |
handle passing helper manager, options handle passing filter chain, options handle passing variables object, options handle passing resolver object, options |
|---|---|
array
Configuration key-value pairs.
canRenderTrees() : boolean
| see | \Zend\View\Renderer\Zend\View\Renderer\TreeRendererInterface |
|---|---|
boolean
getEngine() : \Zend\View\Renderer\ConsoleRenderer
Returns the object instance, as it is its own template engine
\Zend\View\Renderer\ConsoleRenderer
getFilterChain() : \Zend\Filter\FilterChain
init() : void
Triggered by __construct() as its final action.
render(string|\Zend\View\Model\ModelInterface $model, null|array|\Traversable $values = null) : string
null|array|\Traversable
Values to use when rendering. If none provided, uses those in the composed variables container.
string
Console output.
setFilterChain(\Zend\Filter\FilterChain $filters) : \Zend\View\Renderer\ConsoleRenderer
setResolver(\Zend\View\Resolver\ResolverInterface $resolver) : \Zend\View\Renderer\RendererInterface
\Zend\View\Resolver\ResolverInterface
\Zend\View\Renderer\RendererInterface


An example of a Horizontal Bar chart which has the Y-axis centered. The chart has a draw
event attached to it so that when the draw()
function is called a small bit of text is added to the bottom right of the SVG tag that serves as a label showing what the X-axis represents.
 Put this where you want the chart to show up:

This is the code that generates the chart - it should be placed AFTER the

tag:


Shapes Predictor
Input folder name of where model.json is located in shapes-model folder
Model
Load Model
Loaded model:
Predict
Enable Live Prediction


A project base for building modern JavaScript applications
Features
- Not a framework, but a base project to help you structure your JavaScript code and files.
- Makes use of the Mediator Pattern, so you can trigger events around your application.
- Templating built in - Handlebars is included but feel free to change engines.
- Follows the Object Literal Pattern with one global namespace, usually 'MyApp' or 'ChatApp'. In this case, it's 'App'.
- Included: jQuery, Underscore.js and Handlebars.
- A fully commented source to show you why it's doing what it's doing and how to build upon it's foundation.
- The JavaScript version of the HTML5 Boilerplate.
It's actually powering this page.
GitHub
Tweet


Jensen Dynamics
®
News
|
Login

Products

Software

Education

Contact
Please Email us at<EMAIL_ADDRESS>© 2014 Jensen Dynamics | Legal | Jobs | Privacy | Contact |
Webmaster


|
lubyk
0.5
|
#include <Registration.h>
Inherits mdns::AbstractRegistration, and lubyk::LuaObject.
Public Member Functions | |
| Registration (const char *service_type, const char *name, uint port, const char *txt) | |
| ~Registration () | |
| int | fd () |
| LuaStackSize | getService (lua_State *L) |
Register a service for a given service type.
Definition at line 46 of file Registration.h.
| mdns::Registration::Registration | ( | const char * | service_type, |
| const char * | name, | ||
| uint | port, | ||
| const char * | txt | ||
| ) | [inline] |
Definition at line 50 of file Registration.h.
| mdns::Registration::~Registration | ( | ) | [inline] |
Definition at line 54 of file Registration.h.
| int mdns::Registration::fd | ( | ) | [inline] |
Definition at line 57 of file Registration.h.
| LuaStackSize mdns::Registration::getService | ( | lua_State * | L | ) | [inline] |
Get a table describing the service.
Definition at line 64 of file Registration.h.


Angular 2 + Typescript + NgRedux
14
1,123
React Native + Socket.io
14
8,124
React + Typescript + Webpack
101
10,125
Backbone + LESS + Gulp + Handlebars + Redux
101
10,125
React + Typescript + Webpack
101
10,125
React + Typescript + Webpack
101
10,125
React + Typescript + Webpack
101
10,125


Diagram Scene Example
The Diagram Scene example is an application in which you can create a flowchart diagram. It is possible to add flowchart shapes and text and connect the shapes by arrows as shown in the image above. The shapes, arrows, and text can be given different colors, and it is possible to change the font, style, and underline of the text.
The Qt graphics view framework is designed to manage and display custom 2D graphics items. The main classes of the framework are QGraphicsItem, QGraphicsScene and QGraphicsView. The graphics scene manages the items and provides a surface for them. QGraphicsView is a widget that is used to render a scene on the screen. See the Graphics View Framework for a more detailed description of the framework.
In this example we show how to create such custom graphics scenes and items by implementing classes that inherit QGraphicsScene and QGraphicsItem.
In particular we show how to:
- Create custom graphics items.
- Handle mouse events and movement of items.
- Implement a graphics scene that can manage our custom items.
- Custom painting of items.
- Create a movable and editable text item.
The example consists of the following classes:
MainWindow
creates the widgets and display them in a QMainWindow. It also manages the interaction between the widgets and the graphics scene, view and items.DiagramItem
inherits QGraphicsPolygonItem and represents a flowchart shape.TextDiagramItem
inherits QGraphicsTextItem and represents text items in the diagram. The class adds support for moving the item with the mouse, which is not supported by QGraphicsTextItem.Arrow
inherits QGraphicsLineItem and is an arrow that connect two DiagramItems.DiagramScene
inherits QGraphicsDiagramScene and provides support forDiagramItem
,Arrow
andDiagramTextItem
(In addition to the support already handled by QGraphicsScene).
MainWindow Class Definition
class MainWindow : public QMainWindow { Q_OBJECT public: MainWindow(); private slots: void backgroundButtonGroupClicked(QAbstractButton *button); void buttonGroupClicked(int id); void deleteItem(); void pointerGroupClicked(int id); void bringToFront(); void sendToBack(); void itemInserted(DiagramItem *item); void textInserted(QGraphicsTextItem *item); void currentFontChanged(const QFont &font); void fontSizeChanged(const QString &size); void sceneScaleChanged(const QString &scale); void textColorChanged(); void itemColorChanged(); void lineColorChanged(); void textButtonTriggered(); void fillButtonTriggered(); void lineButtonTriggered(); void handleFontChange(); void itemSelected(QGraphicsItem *item); void about(); private: void createToolBox(); void createActions(); void createMenus(); void createToolbars(); QWidget *createBackgroundCellWidget(const QString &text, const QString &image); QWidget *createCellWidget(const QString &text, DiagramItem::DiagramType type); QMenu *createColorMenu(const char *slot, QColor defaultColor); QIcon createColorToolButtonIcon(const QString &image, QColor color); QIcon createColorIcon(QColor color); DiagramScene *scene; QGraphicsView *view; QAction *exitAction; QAction *addAction; QAction *deleteAction; QAction *toFrontAction; QAction *sendBackAction; QAction *aboutAction; QMenu *fileMenu; QMenu *itemMenu; QMenu *aboutMenu; QToolBar *textToolBar; QToolBar *editToolBar; QToolBar *colorToolBar; QToolBar *pointerToolbar; QComboBox *sceneScaleCombo; QComboBox *itemColorCombo; QComboBox *textColorCombo; QComboBox *fontSizeCombo; QFontComboBox *fontCombo; QToolBox *toolBox; QButtonGroup *buttonGroup; QButtonGroup *pointerTypeGroup; QButtonGroup *backgroundButtonGroup; QToolButton *fontColorToolButton; QToolButton *fillColorToolButton; QToolButton *lineColorToolButton; QAction *boldAction; QAction *underlineAction; QAction *italicAction; QAction *textAction; QAction *fillAction; QAction *lineAction; };
The MainWindow
class creates and lays out the widgets in a QMainWindow. The class forwards input from the widgets to the DiagramScene. It also updates its widgets when the diagram scene's text item changes, or a diagram item or a diagram text item is inserted into the scene.
The class also deletes items from the scene and handles the z-ordering, which decides the order in which items are drawn when they overlap each other.
MainWindow Class Implementation
We start with a look at the constructor:
MainWindow::MainWindow() { createActions(); createToolBox(); createMenus(); scene = new DiagramScene(itemMenu, this); scene->setSceneRect(QRectF(0, 0, 5000, 5000)); connect(scene, SIGNAL(itemInserted(DiagramItem*)), this, SLOT(itemInserted(DiagramItem*))); connect(scene, SIGNAL(textInserted(QGraphicsTextItem*)), this, SLOT(textInserted(QGraphicsTextItem*))); connect(scene, SIGNAL(itemSelected(QGraphicsItem*)), this, SLOT(itemSelected(QGraphicsItem*))); createToolbars(); QHBoxLayout *layout = new QHBoxLayout; layout->addWidget(toolBox); view = new QGraphicsView(scene); layout->addWidget(view); QWidget *widget = new QWidget; widget->setLayout(layout); setCentralWidget(widget); setWindowTitle(tr("Diagramscene")); setUnifiedTitleAndToolBarOnMac(true); }
In the constructor we call methods to create the widgets and layouts of the example before we create the diagram scene. The toolbars must be created after the scene as they connect to its signals. We then lay the widgets out in the window.
We connect to the itemInserted()
and textInserted()
slots of the diagram scenes as we want to uncheck the buttons in the tool box when an item is inserted. When an item is selected in the scene we receive the itemSelected()
signal. We use this to update the widgets that display font properties if the item selected is a DiagramTextItem
.
The createToolBox()
function creates and lays out the widgets of the toolBox
QToolBox. We will not examine it with a high level of detail as it does not deal with graphics framework specific functionality. Here is its implementation:
void MainWindow::createToolBox() { buttonGroup = new QButtonGroup(this); buttonGroup->setExclusive(false); connect(buttonGroup, SIGNAL(buttonClicked(int)), this, SLOT(buttonGroupClicked(int))); QGridLayout *layout = new QGridLayout; layout->addWidget(createCellWidget(tr("Conditional"), DiagramItem::Conditional), 0, 0); layout->addWidget(createCellWidget(tr("Process"), DiagramItem::Step),0, 1); layout->addWidget(createCellWidget(tr("Input/Output"), DiagramItem::Io), 1, 0);
This part of the function sets up the tabbed widget item that contains the flowchart shapes. An exclusive QButtonGroup always keeps one button checked; we want the group to allow all buttons to be unchecked. We still use a button group since we can associate user data, which we use to store the diagram type, with each button. The createCellWidget()
function sets up the buttons in the tabbed widget item and is examined later.
The buttons of the background tabbed widget item is set up in the same way, so we skip to the creation of the tool box:
toolBox = new QToolBox; toolBox->setSizePolicy(QSizePolicy(QSizePolicy::Maximum, QSizePolicy::Ignored)); toolBox->setMinimumWidth(itemWidget->sizeHint().width()); toolBox->addItem(itemWidget, tr("Basic Flowchart Shapes")); toolBox->addItem(backgroundWidget, tr("Backgrounds")); }
We set the preferred size of the toolbox as its maximum. This way, more space is given to the graphics view.
Here is the createActions()
function:
void MainWindow::createActions() { toFrontAction = new QAction(QIcon(":/images/bringtofront.png"), tr("Bring to &Front"), this); toFrontAction->setShortcut(tr("Ctrl+F")); toFrontAction->setStatusTip(tr("Bring item to front")); connect(toFrontAction, SIGNAL(triggered()), this, SLOT(bringToFront()));
We show an example of the creation of an action. The functionality the actions trigger is discussed in the slots we connect the actions to. You can see the application example if you need a high-level introduction to actions.
The is the createMenus()
function:
void MainWindow::createMenus() { fileMenu = menuBar()->addMenu(tr("&File")); fileMenu->addAction(exitAction); itemMenu = menuBar()->addMenu(tr("&Item")); itemMenu->addAction(deleteAction); itemMenu->addSeparator(); itemMenu->addAction(toFrontAction); itemMenu->addAction(sendBackAction); aboutMenu = menuBar()->addMenu(tr("&Help")); aboutMenu->addAction(aboutAction); }
We create the three menus' of the example.
The createToolbars()
function sets up the examples tool bars. The three QToolButtons in the colorToolBar
, the fontColorToolButton
, fillColorToolButton
, and lineColorToolButton
, are interesting as we create icons for them by drawing on a QPixmap with a QPainter. We show how the fillColorToolButton
is created. This button lets the user select a color for the diagram items.
void MainWindow::createToolbars() { ... fillColorToolButton = new QToolButton; fillColorToolButton->setPopupMode(QToolButton::MenuButtonPopup); fillColorToolButton->setMenu(createColorMenu(SLOT(itemColorChanged()), Qt::white)); fillAction = fillColorToolButton->menu()->defaultAction(); fillColorToolButton->setIcon(createColorToolButtonIcon( ":/images/floodfill.png", Qt::white)); connect(fillColorToolButton, SIGNAL(clicked()), this, SLOT(fillButtonTriggered()));
We set the menu of the tool button with setMenu(). We need the fillAction
QAction object to always be pointing to the selected action of the menu. The menu is created with the createColorMenu()
function and, as we shall see later, contains one menu item for each color that the items can have. When the user presses the button, which trigger the clicked() signal, we can set the color of the selected item to the color of fillAction
. It is with createColorToolButtonIcon()
we create the icon for the button.
... }
Here is the createBackgroundCellWidget()
function:
QWidget *MainWindow::createBackgroundCellWidget(const QString &text, const QString &image) { QToolButton *button = new QToolButton; button->setText(text); button->setIcon(QIcon(image)); button->setIconSize(QSize(50, 50)); button->setCheckable(true); backgroundButtonGroup->addButton(button); QGridLayout *layout = new QGridLayout; layout->addWidget(button, 0, 0, Qt::AlignHCenter); layout->addWidget(new QLabel(text), 1, 0, Qt::AlignCenter); QWidget *widget = new QWidget; widget->setLayout(layout); return widget; }
This function creates QWidgets containing a tool button and a label. The widgets created with this function are used for the background tabbed widget item in the tool box.
Here is the createCellWidget()
function:
QWidget *MainWindow::createCellWidget(const QString &text, DiagramItem::DiagramType type) { DiagramItem item(type, itemMenu); QIcon icon(item.image()); QToolButton *button = new QToolButton; button->setIcon(icon); button->setIconSize(QSize(50, 50)); button->setCheckable(true); buttonGroup->addButton(button, int(type)); QGridLayout *layout = new QGridLayout; layout->addWidget(button, 0, 0, Qt::AlignHCenter); layout->addWidget(new QLabel(text), 1, 0, Qt::AlignCenter); QWidget *widget = new QWidget; widget->setLayout(layout); return widget; }
This function returns a QWidget containing a QToolButton with an image of one of the DiagramItems
, i.e., flowchart shapes. The image is created by the DiagramItem
through the image()
function. The QButtonGroup class lets us attach an id (int) with each button; we store the diagram's type, i.e., the DiagramItem::DiagramType enum. We use the stored diagram type when we create new diagram items for the scene. The widgets created with this function is used in the tool box.
Here is the createColorMenu()
function:
QMenu *MainWindow::createColorMenu(const char *slot, QColor defaultColor) { QList<QColor> colors; colors << Qt::black << Qt::white << Qt::red << Qt::blue << Qt::yellow; QStringList names; names << tr("black") << tr("white") << tr("red") << tr("blue") << tr("yellow"); QMenu *colorMenu = new QMenu(this); for (int i = 0; i < colors.count(); ++i) { QAction *action = new QAction(names.at(i), this); action->setData(colors.at(i)); action->setIcon(createColorIcon(colors.at(i))); connect(action, SIGNAL(triggered()), this, slot); colorMenu->addAction(action); if (colors.at(i) == defaultColor) colorMenu->setDefaultAction(action); } return colorMenu; }
This function creates a color menu that is used as the drop-down menu for the tool buttons in the colorToolBar
. We create an action for each color that we add to the menu. We fetch the actions data when we set the color of items, lines, and text.
Here is the createColorToolButtonIcon()
function:
QIcon MainWindow::createColorToolButtonIcon(const QString &imageFile, QColor color) { QPixmap pixmap(50, 80); pixmap.fill(Qt::transparent); QPainter painter(&pixmap); QPixmap image(imageFile); // Draw icon centred horizontally on button. QRect target(4, 0, 42, 43); QRect source(0, 0, 42, 43); painter.fillRect(QRect(0, 60, 50, 80), color); painter.drawPixmap(target, image, source); return QIcon(pixmap); }
This function is used to create the QIcon of the fillColorToolButton
, fontColorToolButton
, and lineColorToolButton
. The imageFile string is either the text, flood-fill, or line symbol that is used for the buttons. Beneath the image we draw a filled rectangle using color.
Here is the createColorIcon()
function:
QIcon MainWindow::createColorIcon(QColor color) { QPixmap pixmap(20, 20); QPainter painter(&pixmap); painter.setPen(Qt::NoPen); painter.fillRect(QRect(0, 0, 20, 20), color); return QIcon(pixmap); }
This function creates an icon with a filled rectangle in the color of color. It is used for creating icons for the color menus in the fillColorToolButton
, fontColorToolButton
, and lineColorToolButton
.
Here is the backgroundButtonGroupClicked()
slot:
void MainWindow::backgroundButtonGroupClicked(QAbstractButton *button) { QList<QAbstractButton *> buttons = backgroundButtonGroup->buttons(); foreach (QAbstractButton *myButton, buttons) { if (myButton != button) button->setChecked(false); } QString text = button->text(); if (text == tr("Blue Grid")) scene->setBackgroundBrush(QPixmap(":/images/background1.png")); else if (text == tr("White Grid")) scene->setBackgroundBrush(QPixmap(":/images/background2.png")); else if (text == tr("Gray Grid")) scene->setBackgroundBrush(QPixmap(":/images/background3.png")); else scene->setBackgroundBrush(QPixmap(":/images/background4.png")); scene->update(); view->update(); }
In this function we set the QBrush that is used to draw the background of the diagramscene. The background can be a grid of squares of blue, gray, or white tiles, or no grid at all. We have QPixmaps of the tiles from png files that we create the brush with.
When one of the buttons in the background tabbed widget item is clicked we change the brush; we find out which button it is by checking its text.
Here is the implementation of buttonGroupClicked()
:
void MainWindow::buttonGroupClicked(int id) { QList<QAbstractButton *> buttons = buttonGroup->buttons(); foreach (QAbstractButton *button, buttons) { if (buttonGroup->button(id) != button) button->setChecked(false); } if (id == InsertTextButton) { scene->setMode(DiagramScene::InsertText); } else { scene->setItemType(DiagramItem::DiagramType(id)); scene->setMode(DiagramScene::InsertItem); } }
This slot is called when a button in buttonGroup
is checked. When a button is checked the user can click on the graphics view and a DiagramItem
of the selected type will be inserted into the DiagramScene
. We must loop through the buttons in the group to uncheck other buttons as only one button is allowed to be checked at a time.
QButtonGroup
assigns an id to each button. We have set the id of each button to the diagram type, as given by DiagramItem::DiagramType that will be inserted into the scene when it is clicked. We can then use the button id when we set the diagram type with setItemType()
. In the case of text we assigned an id that has a value that is not in the DiagramType enum.
Here is the implementation of deleteItem()
:
void MainWindow::deleteItem() { foreach (QGraphicsItem *item, scene->selectedItems()) { if (item->type() == Arrow::Type) { scene->removeItem(item); Arrow *arrow = qgraphicsitem_cast<Arrow *>(item); arrow->startItem()->removeArrow(arrow); arrow->endItem()->removeArrow(arrow); delete item; } } foreach (QGraphicsItem *item, scene->selectedItems()) { if (item->type() == DiagramItem::Type) qgraphicsitem_cast<DiagramItem *>(item)->removeArrows(); scene->removeItem(item); delete item; } }
This slot deletes the selected item, if any, from the scene. It deletes the arrows first in order to avoid to delete them twice. If the item to be deleted is a DiagramItem
, we also need to delete arrows connected to it; we don't want arrows in the scene that aren't connected to items in both ends.
This is the implementation of pointerGroupClicked():
void MainWindow::pointerGroupClicked(int) { scene->setMode(DiagramScene::Mode(pointerTypeGroup->checkedId())); }
The pointerTypeGroup
decides whether the scene is in ItemMove or InsertLine mode. This button group is exclusive, i.e., only one button is checked at any time. As with the buttonGroup
above we have assigned an id to the buttons that matches values of the DiagramScene::Mode enum, so that we can use the id to set the correct mode.
Here is the bringToFront()
slot:
void MainWindow::bringToFront() { if (scene->selectedItems().isEmpty()) return; QGraphicsItem *selectedItem = scene->selectedItems().first(); QList<QGraphicsItem *> overlapItems = selectedItem->collidingItems(); qreal zValue = 0; foreach (QGraphicsItem *item, overlapItems) { if (item->zValue() >= zValue && item->type() == DiagramItem::Type) zValue = item->zValue() + 0.1; } selectedItem->setZValue(zValue); }
Several items may collide, i.e., overlap, with each other in the scene. This slot is called when the user requests that an item should be placed on top of the items it collides with. QGrapicsItems have a z-value that decides the order in which items are stacked in the scene; you can think of it as the z-axis in a 3D coordinate system. When items collide the items with higher z-values will be drawn on top of items with lower values. When we bring an item to the front we can loop through the items it collides with and set a z-value that is higher than all of them.
Here is the sendToBack()
slot:
void MainWindow::sendToBack() { if (scene->selectedItems().isEmpty()) return; QGraphicsItem *selectedItem = scene->selectedItems().first(); QList<QGraphicsItem *> overlapItems = selectedItem->collidingItems(); qreal zValue = 0; foreach (QGraphicsItem *item, overlapItems) { if (item->zValue() <= zValue && item->type() == DiagramItem::Type) zValue = item->zValue() - 0.1; } selectedItem->setZValue(zValue); }
This slot works in the same way as bringToFront()
described above, but sets a z-value that is lower than items the item that should be send to the back collides with.
This is the implementation of itemInserted()
:
void MainWindow::itemInserted(DiagramItem *item) { pointerTypeGroup->button(int(DiagramScene::MoveItem))->setChecked(true); scene->setMode(DiagramScene::Mode(pointerTypeGroup->checkedId())); buttonGroup->button(int(item->diagramType()))->setChecked(false); }
This slot is called from the DiagramScene
when an item has been added to the scene. We set the mode of the scene back to the mode before the item was inserted, which is ItemMove or InsertText depending on which button is checked in the pointerTypeGroup
. We must also uncheck the button in the in the buttonGroup
.
Here is the implementation of textInserted()
:
void MainWindow::textInserted(QGraphicsTextItem *) { buttonGroup->button(InsertTextButton)->setChecked(false); scene->setMode(DiagramScene::Mode(pointerTypeGroup->checkedId())); }
We simply set the mode of the scene back to the mode it had before the text was inserted.
Here is the currentFontChanged()
slot:
void MainWindow::currentFontChanged(const QFont &) { handleFontChange(); }
When the user requests a font change, by using one of the widgets in the fontToolBar
, we create a new QFont object and set its properties to match the state of the widgets. This is done in handleFontChange()
, so we simply call that slot.
Here is the fontSizeChanged()
slot:
void MainWindow::fontSizeChanged(const QString &) { handleFontChange(); }
When the user requests a font change, by using one of the widgets in the fontToolBar
, we create a new QFont object and set its properties to match the state of the widgets. This is done in handleFontChange()
, so we simply call that slot.
Here is the implementation of sceneScaleChanged()
:
void MainWindow::sceneScaleChanged(const QString &scale) { double newScale = scale.left(scale.indexOf(tr("%"))).toDouble() / 100.0; QMatrix oldMatrix = view->matrix(); view->resetMatrix(); view->translate(oldMatrix.dx(), oldMatrix.dy()); view->scale(newScale, newScale); }
The user can increase or decrease the scale, with the sceneScaleCombo
, the scene is drawn in. It is not the scene itself that changes its scale, but only the view.
Here is the textColorChanged()
slot:
void MainWindow::textColorChanged() { textAction = qobject_cast<QAction *>(sender()); fontColorToolButton->setIcon(createColorToolButtonIcon( ":/images/textpointer.png", qvariant_cast<QColor>(textAction->data()))); textButtonTriggered(); }
This slot is called when an item in the drop-down menu of the fontColorToolButton
is pressed. We need to change the icon on the button to the color of the selected QAction. We keep a pointer to the selected action in textAction
. It is in textButtonTriggered()
we change the text color to the color of textAction
, so we call that slot.
Here is the itemColorChanged()
implementation:
void MainWindow::itemColorChanged() { fillAction = qobject_cast<QAction *>(sender()); fillColorToolButton->setIcon(createColorToolButtonIcon( ":/images/floodfill.png", qvariant_cast<QColor>(fillAction->data()))); fillButtonTriggered(); }
This slot handles requests for changing the color of DiagramItems
in the same manner as textColorChanged()
does for DiagramTextItems
.
Here is the implementation of lineColorChanged()
:
void MainWindow::lineColorChanged() { lineAction = qobject_cast<QAction *>(sender()); lineColorToolButton->setIcon(createColorToolButtonIcon( ":/images/linecolor.png", qvariant_cast<QColor>(lineAction->data()))); lineButtonTriggered(); }
This slot handles requests for changing the color of Arrows
in the same manner that textColorChanged()
does it for DiagramTextItems
.
Here is the textButtonTriggered()
slot:
void MainWindow::textButtonTriggered() { scene->setTextColor(qvariant_cast<QColor>(textAction->data())); }
textAction
points to the QAction of the currently selected menu item in the fontColorToolButton
's color drop-down menu. We have set the data of the action to the QColor the action represents, so we can simply fetch this when we set the color of text with setTextColor()
.
Here is the fillButtonTriggered()
slot:
void MainWindow::fillButtonTriggered() { scene->setItemColor(qvariant_cast<QColor>(fillAction->data())); }
fillAction
points to the selected menu item in the drop-down menu of fillColorToolButton()
. We can therefore use the data of this action when we set the item color with setItemColor()
.
Here is the lineButtonTriggered()
slot:
void MainWindow::lineButtonTriggered() { scene->setLineColor(qvariant_cast<QColor>(lineAction->data())); }
lineAction
point to the selected item in the drop-down menu of lineColorToolButton
. We use its data when we set the arrow color with setLineColor()
.
Here is the handleFontChange()
function:
void MainWindow::handleFontChange() { QFont font = fontCombo->currentFont(); font.setPointSize(fontSizeCombo->currentText().toInt()); font.setWeight(boldAction->isChecked() ? QFont::Bold : QFont::Normal); font.setItalic(italicAction->isChecked()); font.setUnderline(underlineAction->isChecked()); scene->setFont(font); }
handleFontChange()
is called when any of the widgets that show font properties changes. We create a new QFont object and set its properties based on the widgets. We then call the setFont()
function of DiagramScene
; it is the scene that set the font of the DiagramTextItems
it manages.
Here is the itemSelected()
slot:
void MainWindow::itemSelected(QGraphicsItem *item) { DiagramTextItem *textItem = qgraphicsitem_cast<DiagramTextItem *>(item); QFont font = textItem->font(); fontCombo->setCurrentFont(font); fontSizeCombo->setEditText(QString().setNum(font.pointSize())); boldAction->setChecked(font.weight() == QFont::Bold); italicAction->setChecked(font.italic()); underlineAction->setChecked(font.underline()); }
This slot is called when an item in the DiagramScene
is selected. In the case of this example it is only text items that emit signals when they are selected, so we do not need to check what kind of graphics item is.
We set the state of the widgets to match the properties of the font of the selected text item.
This is the about()
slot:
void MainWindow::about() { QMessageBox::about(this, tr("About Diagram Scene"), tr("The <b>Diagram Scene</b> example shows " "use of the graphics framework.")); }
This slot displays an about box for the example when the user selects the about menu item from the help menu.
DiagramScene Class Definition
The DiagramScene
class inherits QGraphicsScene and adds functionality to handle DiagramItems
, Arrows
, and DiagramTextItems
in addition to the items handled by its super class.
class DiagramScene : public QGraphicsScene { Q_OBJECT public: enum Mode { InsertItem, InsertLine, InsertText, MoveItem }; explicit DiagramScene(QMenu *itemMenu, QObject *parent = 0); QFont font() const { return myFont; } QColor textColor() const { return myTextColor; } QColor itemColor() const { return myItemColor; } QColor lineColor() const { return myLineColor; } void setLineColor(const QColor &color); void setTextColor(const QColor &color); void setItemColor(const QColor &color); void setFont(const QFont &font); public slots: void setMode(Mode mode); void setItemType(DiagramItem::DiagramType type); void editorLostFocus(DiagramTextItem *item); signals: void itemInserted(DiagramItem *item); void textInserted(QGraphicsTextItem *item); void itemSelected(QGraphicsItem *item); protected: void mousePressEvent(QGraphicsSceneMouseEvent *mouseEvent) override; void mouseMoveEvent(QGraphicsSceneMouseEvent *mouseEvent) override; void mouseReleaseEvent(QGraphicsSceneMouseEvent *mouseEvent) override; private: bool isItemChange(int type); DiagramItem::DiagramType myItemType; QMenu *myItemMenu; Mode myMode; bool leftButtonDown; QPointF startPoint; QGraphicsLineItem *line; QFont myFont; DiagramTextItem *textItem; QColor myTextColor; QColor myItemColor; QColor myLineColor; };
In the DiagramScene
a mouse click can give three different actions: the item under the mouse can be moved, an item may be inserted, or an arrow may be connected between to diagram items. Which action a mouse click has depends on the mode, given by the Mode enum, the scene is in. The mode is set with the setMode()
function.
The scene also sets the color of its items and the font of its text items. The colors and font used by the scene can be set with the setLineColor()
, setTextColor()
, setItemColor()
and setFont()
functions. The type of DiagramItem
, given by the DiagramItem::DiagramType function, to be created when an item is inserted is set with the setItemType()
slot.
The MainWindow
and DiagramScene
share responsibility for the examples functionality. MainWindow
handles the following tasks: the deletion of items, text, and arrows; moving diagram items to the back and front; and setting the scale of the scene.
DiagramScene Class Implementation
We start with the constructor:
DiagramScene::DiagramScene(QMenu *itemMenu, QObject *parent) : QGraphicsScene(parent) { myItemMenu = itemMenu; myMode = MoveItem; myItemType = DiagramItem::Step; line = 0; textItem = 0; myItemColor = Qt::white; myTextColor = Qt::black; myLineColor = Qt::black; }
The scene uses myItemMenu
to set the context menu when it creates DiagramItems
. We set the default mode to DiagramScene::MoveItem
as this gives the default behavior of QGraphicsScene.
Here is the setLineColor()
function:
void DiagramScene::setLineColor(const QColor &color) { myLineColor = color; if (isItemChange(Arrow::Type)) { Arrow *item = qgraphicsitem_cast<Arrow *>(selectedItems().first()); item->setColor(myLineColor); update(); } }
The isItemChange
function returns true if an Arrow
item is selected in the scene in which case we want to change its color. When the DiagramScene
creates and adds new arrows to the scene it will also use the new color.
Here is the setTextColor()
function:
void DiagramScene::setTextColor(const QColor &color) { myTextColor = color; if (isItemChange(DiagramTextItem::Type)) { DiagramTextItem *item = qgraphicsitem_cast<DiagramTextItem *>(selectedItems().first()); item->setDefaultTextColor(myTextColor); } }
This function sets the color of DiagramTextItems
equal to the way setLineColor()
sets the color of Arrows
.
Here is the setItemColor()
function:
void DiagramScene::setItemColor(const QColor &color) { myItemColor = color; if (isItemChange(DiagramItem::Type)) { DiagramItem *item = qgraphicsitem_cast<DiagramItem *>(selectedItems().first()); item->setBrush(myItemColor); } }
This function sets the color the scene will use when creating DiagramItems
. It also changes the color of a selected DiagramItem
.
This is the implementation of setFont()
:
void DiagramScene::setFont(const QFont &font) { myFont = font; if (isItemChange(DiagramTextItem::Type)) { QGraphicsTextItem *item = qgraphicsitem_cast<DiagramTextItem *>(selectedItems().first()); //At this point the selection can change so the first selected item might not be a DiagramTextItem if (item) item->setFont(myFont); } }
Set the font to use for new and selected, if a text item is selected, DiagramTextItems
.
This is the implementation of editorLostFocus()
slot:
void DiagramScene::editorLostFocus(DiagramTextItem *item) { QTextCursor cursor = item->textCursor(); cursor.clearSelection(); item->setTextCursor(cursor); if (item->toPlainText().isEmpty()) { removeItem(item); item->deleteLater(); } }
DiagramTextItems
emit a signal when they lose focus, which is connected to this slot. We remove the item if it has no text. If not, we would leak memory and confuse the user as the items will be edited when pressed on by the mouse.
The mousePressEvent()
function handles mouse press event's different depending on which mode the DiagramScene
is in. We examine its implementation for each mode:
void DiagramScene::mousePressEvent(QGraphicsSceneMouseEvent *mouseEvent) { if (mouseEvent->button() != Qt::LeftButton) return; DiagramItem *item; switch (myMode) { case InsertItem: item = new DiagramItem(myItemType, myItemMenu); item->setBrush(myItemColor); addItem(item); item->setPos(mouseEvent->scenePos()); emit itemInserted(item); break;
We simply create a new DiagramItem
and add it to the scene at the position the mouse was pressed. Note that the origin of its local coordinate system will be under the mouse pointer position.
case InsertLine: line = new QGraphicsLineItem(QLineF(mouseEvent->scenePos(), mouseEvent->scenePos())); line->setPen(QPen(myLineColor, 2)); addItem(line); break;
The user adds Arrows
to the scene by stretching a line between the items the arrow should connect. The start of the line is fixed in the place the user clicked the mouse and the end follows the mouse pointer as long as the button is held down. When the user releases the mouse button an Arrow
will be added to the scene if there is a DiagramItem
under the start and end of the line. We will see how this is implemented later; here we simply add the line.
case InsertText: textItem = new DiagramTextItem(); textItem->setFont(myFont); textItem->setTextInteractionFlags(Qt::TextEditorInteraction); textItem->setZValue(1000.0); connect(textItem, SIGNAL(lostFocus(DiagramTextItem*)), this, SLOT(editorLostFocus(DiagramTextItem*))); connect(textItem, SIGNAL(selectedChange(QGraphicsItem*)), this, SIGNAL(itemSelected(QGraphicsItem*))); addItem(textItem); textItem->setDefaultTextColor(myTextColor); textItem->setPos(mouseEvent->scenePos()); emit textInserted(textItem);
The DiagramTextItem
is editable when the Qt::TextEditorInteraction flag is set, else it is movable by the mouse. We always want the text to be drawn on top of the other items in the scene, so we set the value to a number higher than other items in the scene.
default: ; } QGraphicsScene::mousePressEvent(mouseEvent); }
We are in MoveItem mode if we get to the default switch; we can then call the QGraphicsScene implementation, which handles movement of items with the mouse. We make this call even if we are in another mode making it possible to add an item and then keep the mouse button pressed down and start moving the item. In the case of text items, this is not possible as they do not propagate mouse events when they are editable.
This is the mouseMoveEvent()
function:
void DiagramScene::mouseMoveEvent(QGraphicsSceneMouseEvent *mouseEvent) { if (myMode == InsertLine && line != 0) { QLineF newLine(line->line().p1(), mouseEvent->scenePos()); line->setLine(newLine); } else if (myMode == MoveItem) { QGraphicsScene::mouseMoveEvent(mouseEvent); } }
We must draw the line if we are in InsertMode and the mouse button is pressed down (the line is not 0). As discussed in mousePressEvent()
the line is drawn from the position the mouse was pressed to the current position of the mouse.
If we are in MoveItem mode, we call the QGraphicsScene implementation, which handles movement of items.
In the mouseReleaseEvent()
function we need to check if an arrow should be added to the scene:
void DiagramScene::mouseReleaseEvent(QGraphicsSceneMouseEvent *mouseEvent) { if (line != 0 && myMode == InsertLine) { QList<QGraphicsItem *> startItems = items(line->line().p1()); if (startItems.count() && startItems.first() == line) startItems.removeFirst(); QList<QGraphicsItem *> endItems = items(line->line().p2()); if (endItems.count() && endItems.first() == line) endItems.removeFirst(); removeItem(line); delete line;
First we need to get the items (if any) under the line's start and end points. The line itself is the first item at these points, so we remove it from the lists. As a precaution, we check if the lists are empty, but this should never happen.
if (startItems.count() > 0 && endItems.count() > 0 && startItems.first()->type() == DiagramItem::Type && endItems.first()->type() == DiagramItem::Type && startItems.first() != endItems.first()) { DiagramItem *startItem = qgraphicsitem_cast<DiagramItem *>(startItems.first()); DiagramItem *endItem = qgraphicsitem_cast<DiagramItem *>(endItems.first()); Arrow *arrow = new Arrow(startItem, endItem); arrow->setColor(myLineColor); startItem->addArrow(arrow); endItem->addArrow(arrow); arrow->setZValue(-1000.0); addItem(arrow); arrow->updatePosition(); } }
Now we check if there are two different DiagramItems
under the lines start and end points. If there are we can create an Arrow
with the two items. The arrow is then added to each item and finally the scene. The arrow must be updated to adjust its start and end points to the items. We set the z-value of the arrow to -1000.0 because we always want it to be drawn under the items.
line = 0; QGraphicsScene::mouseReleaseEvent(mouseEvent); }
Here is the isItemChange()
function:
bool DiagramScene::isItemChange(int type) { foreach (QGraphicsItem *item, selectedItems()) { if (item->type() == type) return true; } return false; }
The scene has single selection, i.e., only one item can be selected at any given time. The foreach will then loop one time with the selected item or none if no item is selected. isItemChange()
is used to check whether a selected item exists and also is of the specified diagram type.
DiagramItem Class Definition
class DiagramItem : public QGraphicsPolygonItem { public: enum { Type = UserType + 15 }; enum DiagramType { Step, Conditional, StartEnd, Io }; DiagramItem(DiagramType diagramType, QMenu *contextMenu, QGraphicsItem *parent = 0); void removeArrow(Arrow *arrow); void removeArrows(); DiagramType diagramType() const { return myDiagramType; } QPolygonF polygon() const { return myPolygon; } void addArrow(Arrow *arrow); QPixmap image() const; int type() const override { return Type;} protected: void contextMenuEvent(QGraphicsSceneContextMenuEvent *event) override; QVariant itemChange(GraphicsItemChange change, const QVariant &value) override; private: DiagramType myDiagramType; QPolygonF myPolygon; QMenu *myContextMenu; QList<Arrow *> arrows; };
The DiagramItem
represents a flowchart shape in the DiagramScene
. It inherits QGraphicsPolygonItem and has a polygon for each shape. The enum DiagramType has a value for each of the flowchart shapes.
The class has a list of the arrows that are connected to it. This is necessary because only the item knows when it is being moved (with the itemChanged()
function) at which time the arrows must be updated. The item can also draw itself onto a QPixmap with the image()
function. This is used for the tool buttons in MainWindow
, see createColorToolButtonIcon()
in MainWindow
.
The Type enum is a unique identifier of the class. It is used by qgraphicsitem_cast()
, which does dynamic casts of graphics items. The UserType constant is the minimum value a custom graphics item type can be.
DiagramItem Class Implementation
We start with a look at the constructor:
DiagramItem::DiagramItem(DiagramType diagramType, QMenu *contextMenu, QGraphicsItem *parent) : QGraphicsPolygonItem(parent) { myDiagramType = diagramType; myContextMenu = contextMenu; QPainterPath path; switch (myDiagramType) { case StartEnd: path.moveTo(200, 50); path.arcTo(150, 0, 50, 50, 0, 90); path.arcTo(50, 0, 50, 50, 90, 90); path.arcTo(50, 50, 50, 50, 180, 90); path.arcTo(150, 50, 50, 50, 270, 90); path.lineTo(200, 25); myPolygon = path.toFillPolygon(); break; case Conditional: myPolygon << QPointF(-100, 0) << QPointF(0, 100) << QPointF(100, 0) << QPointF(0, -100) << QPointF(-100, 0); break; case Step: myPolygon << QPointF(-100, -100) << QPointF(100, -100) << QPointF(100, 100) << QPointF(-100, 100) << QPointF(-100, -100); break; default: myPolygon << QPointF(-120, -80) << QPointF(-70, 80) << QPointF(120, 80) << QPointF(70, -80) << QPointF(-120, -80); break; } setPolygon(myPolygon); setFlag(QGraphicsItem::ItemIsMovable, true); setFlag(QGraphicsItem::ItemIsSelectable, true); setFlag(QGraphicsItem::ItemSendsGeometryChanges, true); }
In the constructor we create the items polygon according to diagramType. QGraphicsItems are not movable or selectable by default, so we must set these properties.
Here is the removeArrow()
function:
void DiagramItem::removeArrow(Arrow *arrow) { int index = arrows.indexOf(arrow); if (index != -1) arrows.removeAt(index); }
removeArrow()
is used to remove Arrow
items when they or DiagramItems
they are connected to are removed from the scene.
Here is the removeArrows()
function:
void DiagramItem::removeArrows() { foreach (Arrow *arrow, arrows) { arrow->startItem()->removeArrow(arrow); arrow->endItem()->removeArrow(arrow); scene()->removeItem(arrow); delete arrow; } }
This function is called when the item is removed from the scene and removes all arrows that are connected to this item. The arrow must be removed from the arrows
list of both its start and end item.
Here is the addArrow()
function:
void DiagramItem::addArrow(Arrow *arrow) { arrows.append(arrow); }
This function simply adds the arrow to the items arrows
list.
Here is the image()
function:
QPixmap DiagramItem::image() const { QPixmap pixmap(250, 250); pixmap.fill(Qt::transparent); QPainter painter(&pixmap); painter.setPen(QPen(Qt::black, 8)); painter.translate(125, 125); painter.drawPolyline(myPolygon); return pixmap; }
This function draws the polygon of the item onto a QPixmap. In this example we use this to create icons for the tool buttons in the tool box.
Here is the contextMenuEvent()
function:
void DiagramItem::contextMenuEvent(QGraphicsSceneContextMenuEvent *event) { scene()->clearSelection(); setSelected(true); myContextMenu->exec(event->screenPos()); }
We show the context menu. As right mouse clicks, which shows the menu, don't select items by default we set the item selected with setSelected(). This is necessary since an item must be selected to change its elevation with the bringToFront
and sendToBack
actions.
This is the implementation of itemChange()
:
QVariant DiagramItem::itemChange(GraphicsItemChange change, const QVariant &value) { if (change == QGraphicsItem::ItemPositionChange) { foreach (Arrow *arrow, arrows) { arrow->updatePosition(); } } return value; }
If the item has moved, we need to update the positions of the arrows connected to it. The implementation of QGraphicsItem does nothing, so we just return value.
DiagramTextItem Class Definition
The TextDiagramItem
class inherits QGraphicsTextItem and adds the possibility to move editable text items. Editable QGraphicsTextItems are designed to be fixed in place and editing starts when the user single clicks on the item. With DiagramTextItem
the editing starts with a double click leaving single click available to interact with and move it.
class DiagramTextItem : public QGraphicsTextItem { Q_OBJECT public: enum { Type = UserType + 3 }; DiagramTextItem(QGraphicsItem *parent = 0); int type() const override { return Type; } signals: void lostFocus(DiagramTextItem *item); void selectedChange(QGraphicsItem *item); protected: QVariant itemChange(GraphicsItemChange change, const QVariant &value) override; void focusOutEvent(QFocusEvent *event) override; void mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event) override; };
We use itemChange()
and focusOutEvent()
to notify the DiagramScene
when the text item loses focus and gets selected.
We reimplement the functions that handle mouse events to make it possible to alter the mouse behavior of QGraphicsTextItem.
DiagramTextItem Implementation
We start with the constructor:
DiagramTextItem::DiagramTextItem(QGraphicsItem *parent) : QGraphicsTextItem(parent) { setFlag(QGraphicsItem::ItemIsMovable); setFlag(QGraphicsItem::ItemIsSelectable); }
We simply set the item movable and selectable, as these flags are off by default.
Here is the itemChange()
function:
QVariant DiagramTextItem::itemChange(GraphicsItemChange change, const QVariant &value) { if (change == QGraphicsItem::ItemSelectedHasChanged) emit selectedChange(this); return value; }
When the item is selected we emit the selectedChanged signal. The MainWindow
uses this signal to update the widgets that display font properties to the font of the selected text item.
Here is the focusOutEvent()
function:
void DiagramTextItem::focusOutEvent(QFocusEvent *event) { setTextInteractionFlags(Qt::NoTextInteraction); emit lostFocus(this); QGraphicsTextItem::focusOutEvent(event); }
DiagramScene
uses the signal emitted when the text item loses focus to remove the item if it is empty, i.e., it contains no text.
This is the implementation of mouseDoubleClickEvent()
:
void DiagramTextItem::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event) { if (textInteractionFlags() == Qt::NoTextInteraction) setTextInteractionFlags(Qt::TextEditorInteraction); QGraphicsTextItem::mouseDoubleClickEvent(event); }
When we receive a double click event, we make the item editable by calling QGraphicsTextItem::setTextInteractionFlags(). We then forward the double-click to the item itself.
Arrow Class Definition
The Arrow
class is a graphics item that connects two DiagramItems
. It draws an arrow head to one of the items. To achieve this the item needs to paint itself and also re implement methods used by the graphics scene to check for collisions and selections. The class inherits QGraphicsLine item, and draws the arrowhead and moves with the items it connects.
class Arrow : public QGraphicsLineItem { public: enum { Type = UserType + 4 }; Arrow(DiagramItem *startItem, DiagramItem *endItem, QGraphicsItem *parent = 0); int type() const override { return Type; } QRectF boundingRect() const override; QPainterPath shape() const override; void setColor(const QColor &color) { myColor = color; } DiagramItem *startItem() const { return myStartItem; } DiagramItem *endItem() const { return myEndItem; } void updatePosition(); protected: void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget = 0) override; private: DiagramItem *myStartItem; DiagramItem *myEndItem; QColor myColor; QPolygonF arrowHead; };
The item's color can be set with setColor()
.
boundingRect()
and shape()
are reimplemented from QGraphicsLineItem and are used by the scene to check for collisions and selections.
Calling updatePosition()
causes the arrow to recalculate its position and arrow head angle. paint()
is reimplemented so that we can paint an arrow rather than just a line between items.
myStartItem
and myEndItem
are the diagram items that the arrow connects. The arrow is drawn with its head to the end item. arrowHead
is a polygon with three vertices's we use to draw the arrow head.
Arrow Class Implementation
The constructor of the Arrow
class looks like this:
Arrow::Arrow(DiagramItem *startItem, DiagramItem *endItem, QGraphicsItem *parent) : QGraphicsLineItem(parent) { myStartItem = startItem; myEndItem = endItem; setFlag(QGraphicsItem::ItemIsSelectable, true); myColor = Qt::black; setPen(QPen(myColor, 2, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin)); }
We set the start and end diagram items of the arrow. The arrow head will be drawn where the line intersects the end item.
Here is the boundingRect()
function:
QRectF Arrow::boundingRect() const { qreal extra = (pen().width() + 20) / 2.0; return QRectF(line().p1(), QSizeF(line().p2().x() - line().p1().x(), line().p2().y() - line().p1().y())) .normalized() .adjusted(-extra, -extra, extra, extra); }
We need to reimplement this function because the arrow is larger than the bounding rectangle of the QGraphicsLineItem. The graphics scene uses the bounding rectangle to know which regions of the scene to update.
Here is the shape()
function:
QPainterPath Arrow::shape() const { QPainterPath path = QGraphicsLineItem::shape(); path.addPolygon(arrowHead); return path; }
The shape function returns a QPainterPath that is the exact shape of the item. The QGraphicsLineItem::shape() returns a path with a line drawn with the current pen, so we only need to add the arrow head. This function is used to check for collisions and selections with the mouse.
Here is the updatePosition()
slot:
void Arrow::updatePosition() { QLineF line(mapFromItem(myStartItem, 0, 0), mapFromItem(myEndItem, 0, 0)); setLine(line); }
This slot updates the arrow by setting the start and end points of its line to the center of the items it connects.
Here is the paint()
function:
void Arrow::paint(QPainter *painter, const QStyleOptionGraphicsItem *, QWidget *) { if (myStartItem->collidesWithItem(myEndItem)) return; QPen myPen = pen(); myPen.setColor(myColor); qreal arrowSize = 20; painter->setPen(myPen); painter->setBrush(myColor);
If the start and end items collide we do not draw the arrow; the algorithm we use to find the point the arrow should be drawn at may fail if the items collide.
We first set the pen and brush we will use for drawing the arrow.
QLineF centerLine(myStartItem->pos(), myEndItem->pos()); QPolygonF endPolygon = myEndItem->polygon(); QPointF p1 = endPolygon.first() + myEndItem->pos(); QPointF p2; QPointF intersectPoint; QLineF polyLine; for (int i = 1; i < endPolygon.count(); ++i) { p2 = endPolygon.at(i) + myEndItem->pos(); polyLine = QLineF(p1, p2); QLineF::IntersectType intersectType = polyLine.intersect(centerLine, &intersectPoint); if (intersectType == QLineF::BoundedIntersection) break; p1 = p2; } setLine(QLineF(intersectPoint, myStartItem->pos()));
We then need to find the position at which to draw the arrowhead. The head should be drawn where the line and the end item intersects. This is done by taking the line between each point in the polygon and check if it intersects with the line of the arrow. Since the line start and end points are set to the center of the items the arrow line should intersect one and only one of the lines of the polygon. Note that the points in the polygon are relative to the local coordinate system of the item. We must therefore add the position of the end item to make the coordinates relative to the scene.
double angle = ::acos(line().dx() / line().length()); if (line().dy() >= 0) angle = (Pi * 2) - angle; QPointF arrowP1 = line().p1() + QPointF(sin(angle + Pi / 3) * arrowSize, cos(angle + Pi / 3) * arrowSize); QPointF arrowP2 = line().p1() + QPointF(sin(angle + Pi - Pi / 3) * arrowSize, cos(angle + Pi - Pi / 3) * arrowSize); arrowHead.clear(); arrowHead << line().p1() << arrowP1 << arrowP2;
We calculate the angle between the x-axis and the line of the arrow. We need to turn the arrow head to this angle so that it follows the direction of the arrow. If the angle is negative we must turn the direction of the arrow.
We can then calculate the three points of the arrow head polygon. One of the points is the end of the line, which now is the intersection between the arrow line and the end polygon. Then we clear the arrowHead
polygon from the previous calculated arrow head and set these new points.
painter->drawLine(line()); painter->drawPolygon(arrowHead); if (isSelected()) { painter->setPen(QPen(myColor, 1, Qt::DashLine)); QLineF myLine = line(); myLine.translate(0, 4.0); painter->drawLine(myLine); myLine.translate(0,-8.0); painter->drawLine(myLine); } }
If the line is selected, we draw two dotted lines that are parallel with the line of the arrow. We do not use the default implementation, which uses boundingRect() because the QRect bounding rectangle is considerably larger than the line.
Files:
- graphicsview/diagramscene/arrow.cpp
- graphicsview/diagramscene/arrow.h
- graphicsview/diagramscene/diagramitem.cpp
- graphicsview/diagramscene/diagramitem.h
- graphicsview/diagramscene/diagramscene.cpp
- graphicsview/diagramscene/diagramscene.h
- graphicsview/diagramscene/diagramtextitem.cpp
- graphicsview/diagramscene/diagramtextitem.h
- graphicsview/diagramscene/mainwindow.cpp
- graphicsview/diagramscene/mainwindow.h
- graphicsview/diagramscene/main.cpp
- graphicsview/diagramscene/diagramscene.pro
- graphicsview/diagramscene/diagramscene.qrc
Images:
- graphicsview/diagramscene/images/background1.png
- graphicsview/diagramscene/images/background2.png
- graphicsview/diagramscene/images/background3.png
- graphicsview/diagramscene/images/background4.png
- graphicsview/diagramscene/images/bold.png
- graphicsview/diagramscene/images/bringtofront.png
- graphicsview/diagramscene/images/delete.png
- graphicsview/diagramscene/images/floodfill.png
- graphicsview/diagramscene/images/italic.png
- graphicsview/diagramscene/images/linecolor.png
- graphicsview/diagramscene/images/linepointer.png
- graphicsview/diagramscene/images/pointer.png
- graphicsview/diagramscene/images/sendtoback.png
- graphicsview/diagramscene/images/textpointer.png
- graphicsview/diagramscene/images/underline.png


extern char **environ;
int execl(const char *path, const char *arg, ...);
int execlp(const char *file, const char *arg, ...);
int execle(const char *path, const char *arg,
..., char * const envp[]);
int execv(const char *path, char *const argv[]);
int execvp(const char *file, char *const argv[]);
int execvpe(const char *file, char *const argv[],
char *const envp[]);
Feature Test Macro Requirements for glibc (see feature_test_macros(7)):
The initial argument for these functions is the name of a file that is to be executed.
The const char *arg and subsequent ellipses in the execl(), execlp(), and execle() functions can be thought of as arg0, arg1, ..., argn. Together they describe a list of one or more pointers to null-terminated strings that represent the argument list available to the executed program. The first argument, by convention, should point to the filename associated with the file being executed. The list of arguments must be terminated by a null pointer, and, since these are variadic functions, this pointer must be cast (char *) NULL.
The execv(), execvp(), and execvpe() functions provide an array of pointers to null-terminated strings that represent the argument list available to the new program. The first argument, by convention, should point to the filename associated with the file being executed. The array of pointers must be terminated by a null pointer.
The execle() and execvpe() functions allow the caller to specify the environment of the executed program via the argument envp. The envp argument is an array of pointers to null-terminated strings and must be terminated by a null pointer. The other functions take the environment for the new process image from the external variable environ in the calling process.
The execlp(), execvp(), and execvpe() functions duplicate the actions of the shell in searching for an executable file if the specified filename does not contain a slash (/) character. The file is sought in the colon-separated list of directory pathnames specified in the PATH environment variable. If this variable isn't defined, the path list defaults to the current directory followed by the list of directories returned by confstr(_CS_PATH). (This confstr(3) call typically returns the value "/bin:/usr/bin".)
If the specified filename includes a slash character, then PATH is ignored, and the file at the specified pathname is executed.
In addition, certain errors are treated specially.
If permission is denied for a file (the attempted execve(2) failed with the error EACCES), these functions will continue searching the rest of the search path. If no other file is found, however, they will return with errno set to EACCES.
If the header of a file isn't recognized (the attempted execve(2) failed with the error ENOEXEC), these functions will execute the shell (/bin/sh) with the path of the file as its first argument. (If this attempt fails, no further searching is done.)
The execvpe() function is a GNU extension.
The behavior of execlp() and execvp() when errors occur while attempting to execute the file is historic practice, but has not traditionally been documented and is not specified by the POSIX standard. BSD (and possibly other systems) do an automatic sleep and retry if ETXTBSY is encountered. Linux treats it as a hard error and returns immediately.
Traditionally, the functions execlp() and execvp() ignored all errors except for the ones described above and ENOMEM and E2BIG, upon which they returned. They now return if any error other than the ones described above occurs.


--- layout: front permalink: /koi/ stylesheet: koi.css --- KOI is a Network Dedicated to Truth Install our node software to join the network and begin helping us keep the internet accountable. Join Now How it works {% include howItWorks.html %}
Install our node software to join the network and begin helping us keep the internet accountable.


Sign Up for Glocal
Already to Glocal?
Login
Name
Email
Password
City
Edinburgh
Karlsruhe
Montreal
Waterloo
Pittsburgh
Charlotte
Urbana-Champaign
Phoenix
Las Vegas
Madison
Cleveland
Country
U.K
Germany
Canada
US
Register